This commit is contained in:
EonaCat authored and Jeroen Saey committed 2026-11-04 07:53:40 +01:00
1 parent 2c5b69bf2c
commit 22dee59f47
132 files changed
+19488 -7027

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
+401
View File
@@ -0,0 +1,401 @@
# Custom Protocol Support in EonaCat.Connections
Custom protocol implementations, allowing you to easily integrate your own protocols (QUIC, HTTP/2, WebSocket, custom binary protocols, etc.) without modifying the core library.
## Quick Start
### Step 1: Implement INetworkProtocol
Create a class that implements the `INetworkProtocol` interface:
```csharp
using System.Net.Sockets;
using EonaCat.Connections.Protocols;
public class CustomProtocol : INetworkProtocol
{
private Socket? _socket;
public string ProtocolName => "MyCustomProtocol";
public bool IsConnected => _socket?.Connected == true;
public bool CanRead => _socket != null;
public bool CanWrite => _socket != null;
public async Task<bool> ConnectAsync(string host, int port, CancellationToken cancellationToken)
{
// Implement connection logic
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
System.Net.Sockets.ProtocolType.Tcp);
var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
connectCts.CancelAfter(TimeSpan.FromSeconds(30));
await _socket.ConnectAsync(host, port, connectCts.Token);
return true;
}
public async Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
if (data?.Length == 0 || _socket == null)
return false;
try
{
// Add custom framing, encryption, compression, etc.
byte[] frame = PrepareFrame(data);
await _socket.SendAsync(new ArraySegment<byte>(frame),
SocketFlags.None, cancellationToken);
return true;
}
catch
{
return false;
}
}
public async Task<byte[]?> ReceiveAsync(CancellationToken cancellationToken)
{
if (_socket == null)
return null;
try
{
var buffer = new byte[4096];
var received = await _socket.ReceiveAsync(
new ArraySegment<byte>(buffer), SocketFlags.None, cancellationToken);
if (received == 0)
return null;
// Parse custom framing
return ParseFrame(buffer, received);
}
catch
{
return null;
}
}
public async Task DisconnectAsync(CancellationToken cancellationToken)
{
await CleanupAsync(cancellationToken);
}
public async Task CleanupAsync(CancellationToken cancellationToken)
{
try
{
_socket?.Shutdown(SocketShutdown.Both);
_socket?.Close();
_socket?.Dispose();
}
catch { }
_socket = null;
await Task.CompletedTask;
}
// Implement configuration methods (can be no-ops if not applicable to your protocol)
public void ConfigureKeepAlive(bool keepAliveEnabled, int timeInSeconds,
int intervalInSeconds, int retryCount) { }
public void ConfigureSsl(bool useSsl, string? serverName,
bool checkCertificateRevocation, bool allowRenegotiation) { }
public void ConfigureBufferSize(int bufferSize) { }
public void ConfigureNagle(bool enableNagle) { }
public void ConfigureRst(bool enableRst) { }
public string? GetRemoteEndPoint() => _socket?.RemoteEndPoint?.ToString();
public string? GetLocalEndPoint() => _socket?.LocalEndPoint?.ToString();
public Socket? GetUnderlyingSocket() => _socket;
public Stream? GetUnderlyingStream() => null;
public void Dispose()
{
try { _socket?.Dispose(); }
catch { }
}
private byte[] PrepareFrame(byte[] data)
{
// Implement your custom frame format
// Example: add length prefix, checksum, headers, etc.
return data;
}
private byte[]? ParseFrame(byte[] buffer, int length)
{
// Parse your custom frame format
return buffer;
}
}
```
### Step 2: Register Your Protocol
Register your custom protocol with the factory (optional but recommended):
```csharp
// Register with a factory function
ProtocolFactory.RegisterProtocol("CUSTOM", () => new CustomProtocol());
// Or with initialization logic
ProtocolFactory.RegisterProtocol("CUSTOM_WITH_CONFIG", () =>
{
var protocol = new CustomProtocol();
// Custom initialization
return protocol;
});
```
### Step 3: Use in Configuration
Create a configuration that uses your custom protocol:
```csharp
var config = new Configuration
{
Host = "example.com",
Port = 8080,
// Option 1: Use factory function directly
ProtocolFactory = () => new CustomProtocol()
// Option 2: Use registered protocol
// ProtocolFactory = () => ProtocolFactory.CreateProtocol("CUSTOM")
};
// Use with NetworkClient
var client = new NetworkClient(config);
await client.ConnectAsync();
// Now communicating via your custom protocol!
// Or use with NetworkServer
var server = new NetworkServer(config);
await server.StartAsync();
```
### Step 4: Switching Between Protocols
Easily switch between protocols at runtime:
```csharp
public Configuration CreateConfig(string protocol)
{
var config = new Configuration
{
Host = "example.com",
Port = 8080,
};
config.ProtocolFactory = protocol.ToUpper() switch
{
"TCP" => () => ProtocolFactory.CreateProtocol("TCP"),
"UDP" => () => ProtocolFactory.CreateProtocol("UDP"),
"CUSTOM" => () => new CustomProtocol(),
_ => () => ProtocolFactory.CreateProtocol("TCP")
};
return config;
}
```
## INetworkProtocol Interface Reference
Your custom protocol must implement these members:
### Properties
- `string ProtocolName` - Returns the name/identifier of your protocol
- `bool IsConnected` - Whether currently connected
- `bool CanRead` - Whether data can be read
- `bool CanWrite` - Whether data can be written
### Core Methods
- `Task<bool> ConnectAsync(string host, int port, CancellationToken cancellationToken)` - Establish connection
- `Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)` - Send data
- `Task<byte[]?> ReceiveAsync(CancellationToken cancellationToken)` - Receive data
- `Task DisconnectAsync(CancellationToken cancellationToken)` - Close connection
- `Task CleanupAsync(CancellationToken cancellationToken)` - Release resources
### Configuration Methods
- `void ConfigureKeepAlive(bool enabled, int timeInSeconds, int intervalInSeconds, int retryCount)` - Configure keep-alive
- `void ConfigureSsl(bool useSsl, string? serverName, bool checkRevocation, bool allowRenegotiation)` - Configure SSL/TLS
- `void ConfigureBufferSize(int bufferSize)` - Set buffer size
- `void ConfigureNagle(bool enableNagle)` - Configure Nagle's algorithm
- `void ConfigureRst(bool enableRst)` - Configure RST on close
### Utility Methods
- `string? GetRemoteEndPoint()` - Get remote endpoint address
- `string? GetLocalEndPoint()` - Get local endpoint address
- `Socket? GetUnderlyingSocket()` - Get underlying socket (return null if not applicable)
- `Stream? GetUnderlyingStream()` - Get underlying stream (return null if not applicable)
### Resource Management
- `void Dispose()` - Clean up resources (implement IDisposable)
## Use Cases
### Custom Framing Protocol
Add protocol-specific framing (length prefixes, checksums, headers):
```csharp
public async Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
// Add 4-byte length prefix
byte[] lengthPrefix = BitConverter.GetBytes(data.Length);
byte[] frame = new byte[lengthPrefix.Length + data.Length];
Array.Copy(lengthPrefix, frame, lengthPrefix.Length);
Array.Copy(data, 0, frame, lengthPrefix.Length, data.Length);
await _socket.SendAsync(new ArraySegment<byte>(frame),
SocketFlags.None, cancellationToken);
return true;
}
```
### Compression Protocol
Implement automatic compression:
```csharp
public async Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
// Compress data before sending
byte[] compressed = CompressData(data);
await _stream.WriteAsync(compressed, 0, compressed.Length, cancellationToken);
return true;
}
public async Task<byte[]?> ReceiveAsync(CancellationToken cancellationToken)
{
byte[] compressed = await ReadCompressedDataAsync(cancellationToken);
// Decompress data after receiving
return DecompressData(compressed);
}
```
### Encryption Protocol
Add encryption on top of transport:
```csharp
private ICryptoTransform? _encryptor;
private ICryptoTransform? _decryptor;
public async Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
// Encrypt data before sending
byte[] encrypted = _encryptor.TransformFinalBlock(data, 0, data.Length);
await _socket.SendAsync(new ArraySegment<byte>(encrypted),
SocketFlags.None, cancellationToken);
return true;
}
```
### WebSocket Protocol
Wrap WebSocket for application-level transport:
```csharp
private WebSocket? _webSocket;
public async Task<bool> ConnectAsync(string host, int port, CancellationToken cancellationToken)
{
var uri = new Uri($"ws://{host}:{port}");
_webSocket = new ClientWebSocket();
await _webSocket.ConnectAsync(uri, cancellationToken);
return true;
}
public async Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
await _webSocket.SendAsync(new ArraySegment<byte>(data),
WebSocketMessageType.Binary, endOfMessage: true, cancellationToken);
return true;
}
```
## Best Practices
1. **Handle Cancellation**: Always respect the CancellationToken parameter
2. **Error Handling**: Return false on send errors, null on receive errors or connection closed
3. **Resource Cleanup**: Ensure Dispose and CleanupAsync properly release resources
4. **Thread Safety**: Use locks if needed for concurrent access
5. **Configuration**: Implement configuration methods even if they're no-ops
6. **Testing**: Test with both NetworkClient and NetworkServer
7. **Timeouts**: Implement connection timeouts in ConnectAsync
8. **State Management**: Track connection state accurately in IsConnected property
## API Reference
### ProtocolFactory
```csharp
// Register a custom protocol
ProtocolFactory.RegisterProtocol(string name, Func<INetworkProtocol> factory);
// Create a protocol instance
INetworkProtocol protocol = ProtocolFactory.CreateProtocol("PROTOCOL_NAME");
INetworkProtocol tcpProtocol = ProtocolFactory.CreateProtocol(ProtocolType.TCP);
// Check if registered
bool registered = ProtocolFactory.IsProtocolRegistered("PROTOCOL_NAME");
// Get all registered protocol names
IEnumerable<string> protocolNames = ProtocolFactory.GetRegisteredProtocols();
// Unregister a protocol (built-in TCP/UDP cannot be unregistered)
ProtocolFactory.UnregisterProtocol("CUSTOM_PROTOCOL");
```
### Configuration
```csharp
var config = new Configuration
{
// Use custom protocol via factory
ProtocolFactory = () => new CustomProtocol(),
// Or use enum for built-in protocols (backward compatible)
// Protocol = ProtocolType.TCP,
Host = "example.com",
Port = 8080,
BufferSize = 8192,
EnableKeepAlive = true,
EnableNagle = false,
EnableRST = true,
// ... other configuration
};
// Configuration automatically applies settings to protocol
// via GetProtocol() method
INetworkProtocol protocol = config.GetProtocol();
```
## Backward Compatibility
The library maintains full backward compatibility:
```csharp
// Old way (still works)
var config = new Configuration
{
Protocol = ProtocolType.TCP // Uses default TCP implementation
};
// New way
var config = new Configuration
{
ProtocolFactory = () => ProtocolFactory.CreateProtocol("TCP")
};
// Or with custom protocol
var config = new Configuration
{
ProtocolFactory = () => new CustomProtocol()
};
```
## Examples
See [CustomProtocolUsageExample](./CustomProtocolUsageExample.cs) for complete working examples.
## Questions
Contact the brasser
+105
View File
@@ -0,0 +1,105 @@
# Custom Protocol Support
The EonaCat.Connections library now provides **extensible protocol support** that allows you to easily integrate custom network protocols without modifying the core library.
## Key Features
### 1. **INetworkProtocol Interface**
A clean, well-defined contract that any protocol implementation must follow:
- `ConnectAsync`, `SendAsync`, `ReceiveAsync`, `DisconnectAsync`
- Configuration methods: `ConfigureKeepAlive`, `ConfigureSsl`, `ConfigureBufferSize`, etc.
- Utility methods: `GetRemoteEndPoint`, `GetLocalEndPoint`, `GetUnderlyingSocket`, `GetUnderlyingStream`
### 2. **ProtocolFactory**
Central registry for managing protocol implementations:
- Register custom protocols: `ProtocolFactory.RegisterProtocol("CUSTOM", () => new CustomProtocol())`
- Create instances: `ProtocolFactory.CreateProtocol("CUSTOM")`
- Query registered protocols: `ProtocolFactory.IsProtocolRegistered("CUSTOM")`
- Get all protocols: `ProtocolFactory.GetRegisteredProtocols()`
- Unregister protocols (except built-in TCP/UDP)
### 3. **Easy Integration with Configuration**
Use protocols with a single line:
```csharp
var config = new Configuration
{
ProtocolFactory = () => new MyCustomProtocol()
};
```
### 4. **Built-in Implementations**
TCP and UDP protocols are provided out-of-the-box:
- `TcpProtocol` - Full TCP support with SSL/TLS, keep-alive, socket options
- `UdpProtocol` - UDP connectionless protocols
### 5. **Backward Compatibility**
Existing code continues to work without changes:
```csharp
// Old way still works
var config = new Configuration { Protocol = ProtocolType.TCP };
// New way for custom protocols
var config = new Configuration { ProtocolFactory = () => new CustomProtocol() };
```
## Use Cases
- **QUIC Protocol** - Modern, low-latency transport
- **HTTP/2 or HTTP/3** - Web-based communication
- **WebSocket** - Browser-compatible real-time communication
- **Custom Binary Protocols** - Application-specific formats
- **Compression Wrappers** - Transparent data compression
- **Encryption Wrappers** - Protocol-level encryption
- **Protocol Composition** - Layered protocol stacks
## Files Added
- `EonaCat.Connections/Protocols/INetworkProtocol.cs` - Protocol interface
- `EonaCat.Connections/Protocols/ProtocolFactory.cs` - Protocol registry
- `EonaCat.Connections/Protocols/TcpProtocol.cs` - TCP implementation
- `EonaCat.Connections/Protocols/UdpProtocol.cs` - UDP implementation
- `EonaCat.Connections/Protocols/CUSTOM_PROTOCOLS.md` - Complete documentation
## Files Modified
- `EonaCat.Connections/Models/Configuration.cs`
- Added `ProtocolFactory` property (optional custom protocol factory)
- Added `GetProtocol()` method (creates and configures protocol instance)
- Maintains backward compatibility with `Protocol` enum
## Getting Started
### 1. Create Your Protocol
Implement `INetworkProtocol`:
```csharp
public class MyProtocol : INetworkProtocol
{
public string ProtocolName => "MyProtocol";
public bool IsConnected => /* ... */;
// Implement required methods...
}
```
### 2. Register (Optional)
```csharp
ProtocolFactory.RegisterProtocol("MY_PROTO", () => new MyProtocol());
```
### 3. Use in Configuration
```csharp
var config = new Configuration
{
ProtocolFactory = () => new MyProtocol(),
Host = "example.com",
Port = 8080
};
var client = new NetworkClient(config);
await client.ConnectAsync();
```
That's it! Your custom protocol is now integrated.
## Questions?
Please contact the Brasser
@@ -12,7 +12,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="EonaCat.Json" Version="2.2.3" />
<PackageReference Include="EonaCat.Json" Version="2.2.5" />
</ItemGroup>
<ItemGroup>
-72
View File
@@ -1,72 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EonaCat.Connections.Client
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
// Root myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(myJsonResponse);
public class Contact
{
public string email { get; set; }
public string phone { get; set; }
}
public class Department
{
public string id { get; set; }
public string name { get; set; }
public Manager manager { get; set; }
}
public class Details
{
public int hoursSpent { get; set; }
public List<string> technologiesUsed { get; set; }
public string completionDate { get; set; }
public string expectedCompletion { get; set; }
}
public class Employee
{
public string id { get; set; }
public string name { get; set; }
public string position { get; set; }
public Department department { get; set; }
public List<Project> projects { get; set; }
}
public class Manager
{
public string id { get; set; }
public string name { get; set; }
public Contact contact { get; set; }
}
public class Project
{
public string projectId { get; set; }
public string projectName { get; set; }
public string startDate { get; set; }
public List<Task> tasks { get; set; }
}
public class Root
{
public Employee employee { get; set; }
}
public class Task
{
public string taskId { get; set; }
public string title { get; set; }
public string status { get; set; }
public Details details { get; set; }
}
}
+512 -90
View File
@@ -1,56 +1,92 @@
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using System.Reflection;
using System.Text;
namespace EonaCat.Connections.Client.Example
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class Program
{
private const bool UseProcessor = true;
private static JsonDataProcessor<dynamic> processor = new JsonDataProcessor<dynamic>();
private const bool IsHeartBeatEnabled = false;
private static int SEND_DELAY_IN_MILLISECONDS = 1000 * 40;
private static List<NetworkClient> _clients = new List<NetworkClient>();
private static long clientCount = 1;
private static long clientsConnected = 0;
private static string _jsonContent;
//public static string SERVER_IP = "10.40.11.22";
public static string SERVER_IP = "127.0.0.1";
private static Dictionary<NetworkClient, JsonDataProcessor<List<Root>>> _clientsProcessors = new Dictionary<NetworkClient, JsonDataProcessor<List<Root>>>();
private static bool testDataProcessor;
static int i = 0;
private static Configuration _configuration;
public static bool WaitForMessage { get; private set; }
public static bool PressEnterForNextMessage { get; private set; }
public static bool ToConsoleOnly { get; private set; } = true;
public static bool ToConsoleOnly { get; private set; }
public static bool UseJson { get; private set; } = true;
public static bool TESTBYTES { get; private set; }
public static bool UseJsonProcessorTest { get; private set; } = true;
public static bool ShowInConsole { get; private set; }
public static bool UseJsonProcessorInternalTest { get; private set; } = true;
public static bool UseTestJsonFive { get; private set; } = true;
public static bool UseTestJsonTen { get; private set; }
public static bool UseTestJsonTwenty { get; private set; }
public static bool UseTestJsonThirty { get; private set; }
public static bool UseTestJsonOneHundred { get; private set; }
public static bool IgnoreAutoDelay { get; private set; }
public static bool IsConnected { get; private set; }
public static bool CheckJsonPayloadMessage { get; set; }
public static bool EnableStressTest { get; private set; } = false;
public static bool EnableLoadTest { get; private set; } = false;
public static async System.Threading.Tasks.Task Main(string[] args)
public static async Task Main(string[] args)
{
_configuration = new Configuration
{
Protocol = ProtocolType.TCP,
Host = SERVER_IP,
Port = 1111,
Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null),
UseAesEncryption = false,
EnableHeartbeat = IsHeartBeatEnabled,
AesPassword = "itudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tincidunt sollicitudin posuere. Phasellus tincidunt sollicitudin posuere. Nam tristique feugiat est vitae mollis.\",\"version\": 8.39},{\"name\": \"Bhupesh Menon\",\"language\": \"Hindi\",\"id\": \"0CEPNRDV98KT3ORP\",\"bio\": \"Maecenas tempus neque ut porttitor malesuada. Phasellus massa ligula, hendrerit eget efficitur eget, tincidunt in ligula. Quisque mauris ligula, efficitur porttitor sodales ac, lacinia non ex. Maecenas quis nisi nunc.\",\"version\": 2.69},{\"name\": \"Rohini Vasav\",\"language\": \"Hindi\",\"id\": \"UEFML43TCGS04KWM\",\"bio\": \"Ut accumsan, est vel fringilla varius, purus augue blandit nisl, eu rhoncus ligula purus vel dolor. Ut maximus, libero nec facilisis fringilla, ex sem sollicitudin leo, non congue tortor ligula in eros. Nam rutrum sollicitudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tinc",
EnableConnectionDebugLogs = true,
};
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
Console.WriteLine("[TCP Client] Application terminating, forcing cleanup...");
CleanupAllClients();
};
try
{
if (!EnableLoadTest && !EnableStressTest)
{
for (long i = 0; i < clientCount; i++)
{
var clientName = $"User {i}";
var client = await CreateClientAsync().ConfigureAwait(false);
_clients.Add(client);
if (testDataProcessor)
{
_clientsProcessors[client] = new JsonDataProcessor<List<Root>>();
}
else
{
_ = StartClientAsync(clientName, client);
}
}
while (true)
processor.OnProcessMessage += Processor_OnProcessMessage;
processor.OnProcessTextMessage += Processor_OnProcessTextMessage;
processor.OnError += Processor_OnError;
processor.OnClientRemovedDueToIdle += Processor_OnClientRemovedDueToIdle;
if (!IgnoreAutoDelay)
{
SetDelay();
}
bool shouldExit = false;
while (!shouldExit)
{
string message = string.Empty;
@@ -58,18 +94,50 @@ namespace EonaCat.Connections.Client.Example
{
Console.Write("Enter message to send (or 'exit' to quit): ");
message = Console.ReadLine();
}
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
foreach (var client in _clients)
{
await client.DisconnectAsync().ConfigureAwait(false);
}
Console.WriteLine("Disconnected all clients. Press any key to continue...");
Console.ReadKey();
Console.ReadLine();
foreach (var client in _clients)
{
await client.ConnectAsync().ConfigureAwait(false);
}
Console.WriteLine("Reconnected all clients");
}
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
shouldExit = true;
break;
}
var jsonUrl = "https://sample.json-format.com/api/download?url=https%3A%2F%2Ffiles.jsons.live%2Femployees%2F5-level%2F20-MB%2Fformatted.json&name=20%20MB%205%20Level%20Formatted.json";
if (!string.IsNullOrEmpty(message) && message.Equals("connect", StringComparison.OrdinalIgnoreCase))
{
foreach (var client in _clients)
{
await client.ConnectAsync().ConfigureAwait(false);
}
continue;
}
if (EnableStressTest)
{
await RunStressTestAsync();
return;
}
if (EnableLoadTest)
{
await RunLoadTestAsync(10_000, 10, 1000, 10_000);
return;
}
var jsonUrl = "https://samples.json-format.com/employees/json/employees_500KB.json";
try
{
@@ -77,9 +145,6 @@ namespace EonaCat.Connections.Client.Example
{
using var httpClient = new HttpClient();
_jsonContent = await httpClient.GetStringAsync(jsonUrl);
var jsonSize = Encoding.UTF8.GetByteCount(_jsonContent);
WriteToLog($"Using large JSON file (size: {jsonSize / 1024 / 1024} MB)");
}
if (UseJson)
@@ -87,29 +152,41 @@ namespace EonaCat.Connections.Client.Example
message = _jsonContent;
}
if (UseJsonProcessorTest)
if (UseTestJsonTwenty)
{
message = File.ReadAllText("Z:\\json\\20mb.json");
}
if (UseTestJsonThirty)
{
message = File.ReadAllText("Z:\\json\\30mb.json");
}
if (UseTestJsonFive)
{
message = File.ReadAllText("Z:\\json\\5mb.json");
}
if (UseTestJsonTen)
{
message = File.ReadAllText("Z:\\json\\10mb.json");
}
if (UseTestJsonOneHundred)
{
message = File.ReadAllText("Z:\\json\\100mb.json");
}
var jsonSize = Encoding.UTF8.GetByteCount(message);
WriteToLog($"Using file (size: {jsonSize / 1024 / 1024} MB)");
if (UseJsonProcessorInternalTest)
{
foreach (var client in _clients)
{
var processor = _clientsProcessors[client];
processor.OnProcessTextMessage += (sender, e) =>
{
WriteToLog($"Processed message from {e.ClientName}: {e.Text}");
};
processor.OnProcessMessage += (sender, e) =>
{
WriteToLog($"Processed JSON message from {e.ClientName} ({e.ClientEndpoint}): {e.Data}");
};
processor.MaxAllowedBufferSize = 50 * 1024 * 1024; // 10 MB
var json = _jsonContent;
while (true)
{
json = "TEST1" + _jsonContent + "TEST2";
var json = message;
processor.Process(json, "TestClient");
await System.Threading.Tasks.Task.Delay(100).ConfigureAwait(false);
}
await Task.Delay(100).ConfigureAwait(false);
}
}
}
@@ -134,72 +211,360 @@ namespace EonaCat.Connections.Client.Example
}
}
await System.Threading.Tasks.Task.Delay(1000).ConfigureAwait(false);
await Task.Delay(SEND_DELAY_IN_MILLISECONDS).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Console.WriteLine($"[TCP Client] Fatal error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
finally
{
Console.WriteLine("[TCP Client] Stopping all clients...");
CleanupAllClients();
Console.WriteLine("[TCP Client] Stopped.");
}
}
private static async System.Threading.Tasks.Task StartClientAsync(string clientName, NetworkClient client)
private static void CleanupAllClients()
{
foreach (var client in _clients)
{
try
{
client?.Dispose();
}
catch (Exception ex)
{
Console.WriteLine($"Error disposing client: {ex.Message}");
}
}
_clients.Clear();
}
static long totalKeepAlives = 0;
private static async Task KeepAliveBroadCastTest()
{
var client = _clients.FirstOrDefault();
client.OnDataReceived += (sender, e) =>
{
if (e.StringData.Contains("KeepAlive Test"))
{
Console.Title = $"Received KeepAlive Test response at {DateTime.Now} (total {++totalKeepAlives})";
Console.WriteLine($"Received KeepAlive Test response: {e.StringData}");
}
else
{
Console.WriteLine($"Received data: {e.StringData}");
}
};
await client.SendAndWaitForResponseAsync("KeepAliveTest", TimeSpan.FromSeconds(30)).ContinueWith(task =>
{
if (task.IsCompletedSuccessfully)
{
var response = task.Result;
Console.WriteLine($"Received response for KeepAliveTest: {response}");
}
else
{
Console.WriteLine($"KeepAliveTest failed: {task.Exception?.Message}");
}
});
}
private static async Task TimerTest()
{
System.Timers.Timer timer = new System.Timers.Timer(1000);
timer.Elapsed += (sender, e) =>
{
Console.WriteLine("IK BEN GEFIRED!");
};
timer.Start();
while (true)
{
timer.Start();
Console.WriteLine("JIJ BENT EEN NERD !");
await Task.Delay(950);
timer.Stop();
Console.WriteLine("JIJ BENT EEN NERD ! (NA TIMER)");
await Task.Delay(1000).ConfigureAwait(false);
}
}
private static void DelayTest()
{
while (true)
{
_clients.FirstOrDefault().SendAsync($"Hello server, this is a delayed message at {DateTime.Now}").ConfigureAwait(false);
Console.WriteLine($"{DateTime.Now} : Sent delayed message");
Thread.Sleep(30_000);
}
}
private static async Task DisconnectTest()
{
while (true)
{
var client = new NetworkClient(new Configuration()
{
Host = "127.0.0.1",
Port = 1111,
Certificate = CertificateHelper.GetCertificate(certificateThumbprint: "4e34475f8618f4cbd65a9852b8bf45e740a52fff"),
});
client.OnDataReceived += Client_OnDataReceived1;
while (true)
{
await Task.Delay(10000).ConfigureAwait(false);
await client.ConnectAsync().ConfigureAwait(false);
await Task.Delay(1000).ConfigureAwait(false);
await client.DisconnectAsync().ConfigureAwait(false);
await Task.Delay(1000).ConfigureAwait(false);
await client.ConnectAsync().ConfigureAwait(false);
await Task.Delay(1000).ConfigureAwait(false);
await client.DisconnectAsync().ConfigureAwait(false);
await Task.Delay(1000).ConfigureAwait(false);
await client.ConnectAsync().ConfigureAwait(false);
await client.SendAsync("Hallo ik ben een brasser zie je dat niet;");
}
}
}
private static async void Client_OnDataReceived1(object? sender, DataReceivedEventArgs e)
{
var client = (NetworkClient)sender;
if (client == null)
{
return;
}
Console.WriteLine($"Received data from server: {e.StringData}");
await client.SendAsync($"Echo: {e.StringData}").ConfigureAwait(false);
await client.DisconnectAsync().ConfigureAwait(false);
await client.ConnectAsync();
}
private static async Task RikAsync()
{
var client = new NetworkClient(new Configuration()
{
Host = "127.0.0.1",
Port = 1111,
Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null),
EnableConnectionDebugLogs = true,
MessageFraming = FramingMode.LengthPrefixed,
});
client.OnConnected += Client_OnConnected;
client.OnDisconnected += Client_OnDisconnected;
client.OnDataReceived += Client_OnDataReceived;
client.OnGeneralError += Client_OnGeneralError;
client.OnEncryptionError += Client_OnEncryptionError;
client.OnSslError += Client_OnSslError;
await client.ConnectAsync().ConfigureAwait(false);
while (true)
{
await client.ConnectAsync();
await Task.Delay(250);
}
}
private static void Client_OnDataReceived(object? sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
var dataSize = e.Data.Length;
if (CheckJsonPayloadMessage)
{
Console.WriteLine($"Received JSON from server (size: {dataSize} bytes)");
}
else
{
Console.WriteLine($"Received data from server (size: {dataSize} bytes) {e.StringData}");
}
}
else
{
Console.WriteLine("Received data from server (no data)");
}
}
private static void Client_OnDisconnected(object? sender, EventArguments.ConnectionEventArgs e)
{
Console.WriteLine($"Disconnected from server at {e.RemoteEndPoint}");
IsConnected = false;
}
private static void Client_OnConnected(object? sender, EventArguments.ConnectionEventArgs e)
{
Console.WriteLine($"Connected to server at {e.RemoteEndPoint}");
IsConnected = true;
SendMessagesContinuously(sender);
}
private static void SendMessagesContinuously(object? sender)
{
while (IsConnected)
{
var message = $"Hello server, this is message {++i}";
((NetworkClient)sender).SendAsync(message).ConfigureAwait(false);
Console.WriteLine($"{DateTime.Now} : Sent message: {message}");
Thread.Sleep(1);
}
}
private static void Processor_OnClientRemovedDueToIdle(object? sender, string e)
{
Console.WriteLine($"Client removed due to idle: {e}");
}
private static void Processor_OnError(object? sender, Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
private static void Processor_OnProcessTextMessage(object? sender, ProcessedTextMessage e)
{
if (ShowInConsole)
{
Console.WriteLine("Received text: " + e.Text);
}
else
{
Console.WriteLine("Received text OK");
}
}
private static void Processor_OnProcessMessage(object? sender, ProcessedMessage<dynamic> e)
{
if (ShowInConsole)
{
Console.WriteLine("Received JSON message OK: " + e.Data);
}
else
{
Console.WriteLine("Received JSON message OK");
}
}
private static void SetDelay()
{
if (UseTestJsonOneHundred)
{
SEND_DELAY_IN_MILLISECONDS = 1000 * 120;
}
else if (UseTestJsonThirty)
{
SEND_DELAY_IN_MILLISECONDS = 1000 * 60;
}
else if (UseTestJsonTwenty)
{
SEND_DELAY_IN_MILLISECONDS = 1000 * 40;
}
else if (UseTestJsonTen)
{
SEND_DELAY_IN_MILLISECONDS = 1000 * 20;
}
}
private static void SmallMessagesTest()
{
while (true)
{
for (int i = 0; i < 1000; i++)
{
var message = $"{i}";
_clients.ForEach(async client =>
{
await client.SendAsync(message).ConfigureAwait(false);
});
}
Thread.Sleep(10);
}
}
private static async Task DanielTestAsync()
{
Console.WriteLine("SocketTest Client started.");
EonaCat.Connections.NetworkClient _networkClient = new EonaCat.Connections.NetworkClient(new Configuration()
{
Host = "127.0.0.1",
Port = 1111,
});
Console.WriteLine("Connecting to server...");
_ = _networkClient.ConnectAsync();
await Task.Delay(1000);
Console.WriteLine("Disconnecting from server...");
_ = _networkClient.DisconnectAsync();
_ = _networkClient.DisposeAsync();
await _networkClient.ConnectAsync();
_networkClient.Dispose();
_networkClient = null;
while (true)
{
await Task.Delay(1000);
Console.WriteLine("Keeping the process alive...");
}
Console.WriteLine("DanielTest finished...");
Console.ReadKey();
}
private static async Task StartClientAsync(string clientName, NetworkClient client)
{
await client.ConnectAsync().ConfigureAwait(false);
// Send nickname
await client.SendNicknameAsync(clientName);
// Send a message
await client.SendAsync($"Hello server, my name is {clientName}!");
}
private static async Task<NetworkClient> CreateClientAsync()
{
var config = new Configuration
{
Protocol = ProtocolType.TCP,
Host = SERVER_IP,
Port = 1111,
UseAesEncryption = false,
EnableHeartbeat = IsHeartBeatEnabled,
AesPassword = "EonaCat.Connections.Password",
//Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "p@ss"),
};
var client = new NetworkClient(_configuration);
var client = new NetworkClient(config);
// Subscribe to events
client.OnConnected += (sender, e) =>
{
client.SendNicknameAsync("MYTESTNICKNAME");
WriteToLog($"Connected to server at {e.RemoteEndPoint}");
Console.WriteLine($"Connected to server at {e.RemoteEndPoint}");
Console.Title = $"Total clients {++clientsConnected}";
};
}; ;
if (UseProcessor)
client.OnDataReceived += async (sender, e) =>
{
_clientsProcessors[client] = new JsonDataProcessor<List<Root>>();
_clientsProcessors[client].OnError += (sender, e) =>
var data = e.Data;
if (Encoding.UTF8.GetString(data).Contains("Server broadcast"))
{
Console.WriteLine($"Processor error: {e.Message}");
};
_clientsProcessors[client].OnProcessTextMessage += (sender, e) =>
{
Console.WriteLine($"Processed text message from {e.ClientName}: {e.Text}");
};
_clientsProcessors[client].OnProcessMessage += (sender, e) =>
{
ProcessMessage(e.Data, e.ClientName, e.ClientEndpoint ?? "Unknown endpoint");
};
var broadcastData = Encoding.UTF8.GetString(data).Split(new[] { "Server broadcast: " }, StringSplitOptions.None).LastOrDefault()?.Trim();
Console.Title = broadcastData;
return;
}
client.OnDataReceived += (sender, e) =>
Console.WriteLine($"Received: {data.Length} bytes");
if (UseJsonProcessorTest)
{
if (UseProcessor)
{
_clientsProcessors[client].Process(e.StringData, currentClientName: e.Nickname);
processor.Process(e, currentClientName: e.Nickname, e.RemoteEndPoint.ToString());
return;
}
else
{
Console.WriteLine(e.StringData);
return;
WriteToLog($"Server says: {(e.IsBinary ? $"{e.Data.Length} bytes" : "We got a json message")}");
Console.WriteLine($"{e.StringData}");
@@ -235,9 +600,6 @@ namespace EonaCat.Connections.Client.Example
message = $"Disconnected from server (remote close). Reason: {e.Reason}";
}
}
WriteToLog(message);
Console.WriteLine(message);
Console.Title = $"Total clients {--clientsConnected}";
};
@@ -248,8 +610,16 @@ namespace EonaCat.Connections.Client.Example
}
private static void ProcessMessage(object message, string clientName, string remoteEndpoint)
{
if (ShowInConsole)
{
WriteToLog($"Processed message from {clientName} ({remoteEndpoint}): {message}");
}
else
{
WriteToLog($"Processed message from {clientName} ({remoteEndpoint})");
}
if (PressEnterForNextMessage)
{
Console.ReadKey();
@@ -263,12 +633,64 @@ namespace EonaCat.Connections.Client.Example
private static void Client_OnGeneralError(object? sender, EventArguments.ErrorEventArgs e)
{
WriteToLog($"General error: {e.Message} => {e.Exception?.Message} => {e.Nickname}");
WriteToLog($"General error: {e.Message} {e.Exception?.Message} {e.Nickname}");
}
private static void Client_OnEncryptionError(object? sender, EventArguments.ErrorEventArgs e)
{
WriteToLog($"Encryption error: {e.Message} => {e.Exception?.Message} => {e.Nickname}");
WriteToLog($"Encryption error: {e.Message} {e.Exception?.Message} {e.Nickname}");
}
/// <summary>
/// Run a stress test with multiple clients and many messages
/// </summary>
public static async Task RunStressTestAsync(int totalClients = 1000, int totalMessages = 100)
{
try
{
int clients = totalClients;
int messages = totalMessages;
// Close existing clients so stress test can use the port
CleanupAllClients();
await Task.Delay(1000); // Wait for port to be released
var stressTest = new Tests.StressTest(_configuration, clients, messages);
await stressTest.RunAsync();
WriteToLog($"Stress test completed. Report:{Environment.NewLine}{stressTest.Result}");
// Recreate clients if needed
for (long i = 0; i < clientCount; i++)
{
var clientName = $"User {i}";
var client = await CreateClientAsync().ConfigureAwait(false);
_clients.Add(client);
_ = StartClientAsync(clientName, client);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error running stress test: {ex.Message}");
}
finally
{
Console.WriteLine("Stress test completed.");
Console.ReadKey();
}
}
private static async Task RunLoadTestAsync(int totalConnections, int durationMinutes, int connectionRatePerSecond, int messageRate)
{
var tester = new LoadTester(_configuration, totalConnections);
var task = tester.RunAsync(
duration: TimeSpan.FromMinutes(durationMinutes),
connectionRatePerSecond: connectionRatePerSecond, // Establish connections/sec
messageRate: messageRate // messages/sec/connection
);
await task;
var report = tester.GetReport();
WriteToLog($"Load test completed. Report:{Environment.NewLine}{report}");
Console.ReadKey();
}
public static void WriteToLog(string message)
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.OpcUa\EonaCat.Connections.OpcUa.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,41 @@
using EonaCat.Connections.OpcUa.Client;
using EonaCat.Connections.OpcUa.Configuration;
const string endpointUrl = "opc.tcp://localhost:4840/EonaCat/Connector";
const string namespaceUri = "urn:EonaCat:Connector:OpcUa:Example";
await using var client = new OpcUaNetworkClient(new OpcUaClientOptions
{
EndpointUrl = endpointUrl,
UseSecurity = false,
AutoAcceptUntrustedCertificates = true,
CheckCertificateRevocation = false
});
client.Error += (_, exception) => Console.Error.WriteLine(exception);
if (!await client.ConnectAsync())
{
return;
}
var temperatureNode = client.GetNodeId(namespaceUri, "Machine.Temperature");
var enabledNode = client.GetNodeId(namespaceUri, "Machine.Enabled");
var addMethod = client.GetNodeId(namespaceUri, "Machine.Add");
var rootNode = client.GetNodeId(namespaceUri, "EonaCat");
await using var subscription = await client.SubscribeAsync([temperatureNode, enabledNode], (_, args) => Console.WriteLine($"Subscription: {args.NodeId} = {args.Value}"));
var temperature = await client.ReadAsync(temperatureNode);
Console.WriteLine($"Temperature: {temperature.Value}");
await client.WriteAsync(temperatureNode, 42.0d);
var result = await client.CallAsync(rootNode, addMethod, [2.0d, 3.5d]);
Console.WriteLine($"2 + 3.5 = {result[0]}");
var children = await client.BrowseAsync(rootNode);
foreach (var child in children)
{
Console.WriteLine($"{child.NodeClass}: {child.DisplayName} ({child.NodeId})");
}
await Task.Delay(1_500);
Console.ReadKey();
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.OpcUa\EonaCat.Connections.OpcUa.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,39 @@
using EonaCat.Connections.OpcUa.Configuration;
using EonaCat.Connections.OpcUa.Models;
using EonaCat.Connections.OpcUa.Server;
using Opc.Ua;
const string namespaceUri = "urn:EonaCat:Connector:OpcUa:Example";
await using var server = new OpcUaNetworkServer(new OpcUaServerOptions
{
BaseAddress = "opc.tcp://localhost:4840/EonaCat/Connector",
NamespaceUri = namespaceUri,
AutoAcceptUntrustedCertificates = true,
CheckCertificateRevocation = false
});
server.AddVariable(new OpcUaNodeDefinition("Machine.Temperature", "Temperature", DataTypeIds.Double, 1337.0d, Description: "Current machine temperature in degrees Celsius"))
.AddVariable(new OpcUaNodeDefinition("Machine.Enabled", "Enabled", DataTypeIds.Boolean, true))
.AddMethod(new OpcUaMethodDefinition("Machine.Add", "Add",
[
new OpcUaMethodArgument("Left", DataTypeIds.Double),
new OpcUaMethodArgument("Right", DataTypeIds.Double)
],
[new OpcUaMethodArgument("Result", DataTypeIds.Double)], arguments => [Convert.ToDouble(arguments[0]) + Convert.ToDouble(arguments[1])], "Adds two numbers"));
server.ValueChanged += (_, args) => Console.WriteLine($"Value changed: {args.NodeId} = {args.Value}");
server.Error += (_, exception) => Console.Error.WriteLine(exception);
await server.StartAsync();
Console.WriteLine($"OPC UA server listening on {server.EndpointUrl}");
Console.WriteLine("Press Ctrl+C to stop.");
var stopped = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
stopped.TrySetResult(true);
};
await stopped.Task;
@@ -0,0 +1,309 @@
using EonaCat.Connections.OpcUa.Configuration;
using EonaCat.Connections.OpcUa.Infrastructure;
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Client;
using System.Text;
using OpcUaClientOptions = EonaCat.Connections.OpcUa.Configuration.OpcUaClientOptions;
namespace EonaCat.Connections.OpcUa.Client;
public sealed class OpcUaNetworkClient : IAsyncDisposable, IDisposable
{
private readonly OpcUaClientOptions _options;
private readonly SemaphoreSlim _lifecycleLock = new(1, 1);
private ApplicationConfiguration? _configuration;
private ISession? _session;
private SessionReconnectHandler? _reconnectHandler;
private bool _disposed;
public OpcUaNetworkClient(OpcUaClientOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public bool IsConnected => _session?.Connected == true;
public ISession? Session => _session;
public string EndpointUrl => _options.EndpointUrl;
public event EventHandler<OpcUaConnectionEventArgs>? Connected;
public event EventHandler<OpcUaConnectionEventArgs>? Disconnected;
public event EventHandler<Exception>? Error;
public NodeId GetNodeId(string namespaceUri, string identifier)
{
ArgumentException.ThrowIfNullOrWhiteSpace(namespaceUri);
ArgumentException.ThrowIfNullOrWhiteSpace(identifier);
var namespaceIndex = GetSession().NamespaceUris.GetIndex(namespaceUri);
if (namespaceIndex < 0)
{
throw new ArgumentException($"Namespace '{namespaceUri}' is not registered by the server.", nameof(namespaceUri));
}
return new NodeId(identifier, (ushort)namespaceIndex);
}
public async Task<bool> ConnectAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (IsConnected)
{
return true;
}
_configuration ??= await OpcUaApplicationConfigurationFactory
.CreateClientAsync(_options, cancellationToken)
.ConfigureAwait(false);
var endpointDescription = await CoreClientUtils.SelectEndpointAsync(
_configuration,
_options.EndpointUrl,
_options.UseSecurity,
_options.OperationTimeoutMilliseconds,
OpcUaRuntime.Telemetry,
cancellationToken).ConfigureAwait(false);
var endpoint = new ConfiguredEndpoint(
null,
endpointDescription,
EndpointConfiguration.Create(_configuration));
var identity = string.IsNullOrWhiteSpace(_options.Username)
? new UserIdentity()
: new UserIdentity(
_options.Username,
Encoding.UTF8.GetBytes(_options.Password ?? string.Empty));
_session = await OpcUaRuntime.SessionFactory.CreateAsync(
_configuration,
endpoint,
false,
_options.SessionName,
(uint)_options.SessionTimeoutMilliseconds,
identity,
default,
cancellationToken).ConfigureAwait(false);
_session.KeepAlive += HandleKeepAlive;
Connected?.Invoke(this, CreateConnectionEventArgs());
return true;
}
catch (Exception exception)
{
Error?.Invoke(this, exception);
return false;
}
finally
{
_lifecycleLock.Release();
}
}
public async Task<IReadOnlyList<ReferenceDescription>> BrowseAsync(
NodeId? nodeId = null,
CancellationToken cancellationToken = default)
{
var session = GetSession();
var browser = new Browser(session)
{
BrowseDirection = BrowseDirection.Forward,
NodeClassMask = (int)(NodeClass.Object | NodeClass.Variable | NodeClass.Method),
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true
};
var references = await browser.BrowseAsync(nodeId ?? ObjectIds.ObjectsFolder, cancellationToken).ConfigureAwait(false);
return references.ToArray();
}
public async Task<DataValue> ReadAsync(NodeId nodeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(nodeId);
return await GetSession().ReadValueAsync(nodeId, cancellationToken).ConfigureAwait(false);
}
public async Task WriteAsync(NodeId nodeId, object? value, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(nodeId);
var values = new[]
{
new WriteValue
{
NodeId = nodeId,
AttributeId = Attributes.Value,
Value = new DataValue(new Variant(value))
}
};
var response = await GetSession().WriteAsync(null, values, cancellationToken).ConfigureAwait(false);
if (StatusCode.IsBad(response.Results[0]))
{
throw new ServiceResultException(response.Results[0]);
}
}
public async Task<IReadOnlyList<object?>> CallAsync(
NodeId objectId,
NodeId methodId,
IEnumerable<object?>? arguments = null,
CancellationToken cancellationToken = default)
{
var request = new CallMethodRequest
{
ObjectId = objectId,
MethodId = methodId,
InputArguments = (arguments ?? []).Select(value => new Variant(value)).ToArray()
};
var methods = new[] { request };
var response = await GetSession().CallAsync(null, methods, cancellationToken).ConfigureAwait(false);
var result = response.Results[0];
if (StatusCode.IsBad(result.StatusCode))
{
throw new ServiceResultException(result.StatusCode);
}
return result.OutputArguments.ToArray().Select(argument => argument.Value).ToArray();
}
public async Task<OpcUaSubscription> SubscribeAsync(
IEnumerable<NodeId> nodeIds,
EventHandler<OpcUaValueChangedEventArgs> handler,
int publishingIntervalMilliseconds = 1_000,
int samplingIntervalMilliseconds = 1_000,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(nodeIds);
ArgumentNullException.ThrowIfNull(handler);
var session = GetSession();
var subscription = new Subscription(session.DefaultSubscription)
{
PublishingInterval = publishingIntervalMilliseconds
};
foreach (var nodeId in nodeIds)
{
var item = new MonitoredItem(subscription.DefaultItem)
{
StartNodeId = nodeId,
AttributeId = Attributes.Value,
SamplingInterval = samplingIntervalMilliseconds,
QueueSize = 10,
DiscardOldest = true
};
item.Notification += (monitoredItem, _) =>
{
foreach (var value in monitoredItem.DequeueValues())
{
handler(this, new OpcUaValueChangedEventArgs
{
NodeId = nodeId,
Value = value.WrappedValue.Value,
StatusCode = value.StatusCode,
SourceTimestamp = value.SourceTimestamp.ToDateTime()
});
}
};
subscription.AddItem(item);
}
session.AddSubscription(subscription);
await subscription.CreateAsync(cancellationToken).ConfigureAwait(false);
return new OpcUaSubscription(subscription);
}
public async Task DisconnectAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
_reconnectHandler?.Dispose();
_reconnectHandler = null;
if (_session != null)
{
_session.KeepAlive -= HandleKeepAlive;
await _session.CloseAsync(cancellationToken).ConfigureAwait(false);
_session.Dispose();
_session = null;
Disconnected?.Invoke(this, CreateConnectionEventArgs());
}
}
finally
{
_lifecycleLock.Release();
}
}
private ISession GetSession()
{
if (_session?.Connected != true)
{
throw new InvalidOperationException("The OPC UA client is not connected.");
}
return _session;
}
private void HandleKeepAlive(ISession session, KeepAliveEventArgs args)
{
if (ServiceResult.IsGood(args.Status))
{
return;
}
Disconnected?.Invoke(this, CreateConnectionEventArgs());
if (!_options.AutoReconnect || _reconnectHandler != null)
{
return;
}
var currentSession = _session;
if (currentSession == null)
{
return;
}
_reconnectHandler = new SessionReconnectHandler(OpcUaRuntime.Telemetry);
_reconnectHandler.BeginReconnect(
currentSession,
_options.ReconnectPeriodMilliseconds,
(_, _) =>
{
if (_reconnectHandler?.Session is ISession reconnectedSession)
{
_session = reconnectedSession;
_session.KeepAlive += HandleKeepAlive;
Connected?.Invoke(this, CreateConnectionEventArgs());
}
_reconnectHandler?.Dispose();
_reconnectHandler = null;
});
}
private OpcUaConnectionEventArgs CreateConnectionEventArgs() => new()
{
EndpointUrl = _options.EndpointUrl,
SessionName = _session?.SessionName
};
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
await DisconnectAsync().ConfigureAwait(false);
_disposed = true;
_lifecycleLock.Dispose();
}
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
}
@@ -0,0 +1,30 @@
using Opc.Ua.Client;
namespace EonaCat.Connections.OpcUa.Client;
public sealed class OpcUaSubscription : IAsyncDisposable, IDisposable
{
private readonly Subscription _subscription;
private bool _disposed;
internal OpcUaSubscription(Subscription subscription)
{
_subscription = subscription;
}
public uint Id => _subscription.Id;
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
await _subscription.DeleteAsync(true, CancellationToken.None).ConfigureAwait(false);
_subscription.Dispose();
}
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
}
@@ -0,0 +1,20 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Configuration;
public sealed class OpcUaClientOptions
{
public required string EndpointUrl { get; init; }
public string ApplicationName { get; init; } = "EonaCat OPC UA Client";
public string ApplicationUri { get; init; } = $"urn:{Utils.GetHostName()}:EonaCat:OpcUa:Client";
public string SessionName { get; init; } = "EonaCat OPC UA Session";
public string? Username { get; init; }
public string? Password { get; init; }
public bool UseSecurity { get; init; } = true;
public bool AutoAcceptUntrustedCertificates { get; init; }
public bool CheckCertificateRevocation { get; init; } = true;
public bool AutoReconnect { get; init; } = true;
public int ReconnectPeriodMilliseconds { get; init; } = 5_000;
public int SessionTimeoutMilliseconds { get; init; } = 60_000;
public int OperationTimeoutMilliseconds { get; init; } = 15_000;
}
@@ -0,0 +1,19 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Configuration;
public sealed class OpcUaServerOptions
{
public string ApplicationName { get; init; } = "EonaCat OPC UA Server";
public string ApplicationUri { get; init; } = $"urn:{Utils.GetHostName()}:EonaCat:OpcUa:Server";
public string ProductUri { get; init; } = "urn:EonaCat:Connector:OpcUa";
public string BaseAddress { get; init; } = "opc.tcp://localhost:4840/EonaCat/Connector";
public string NamespaceUri { get; init; } = "urn:EonaCat:Connector:OpcUa:AddressSpace";
public bool EnableSecureEndpoint { get; init; } = true;
public bool AllowUnsecuredEndpoint { get; init; } = true;
public bool AutoAcceptUntrustedCertificates { get; init; }
public bool CheckCertificateRevocation { get; init; } = true;
public int OperationTimeoutMilliseconds { get; init; } = 15_000;
public int MaxSessionCount { get; init; } = 100;
public int MaxSubscriptionCount { get; init; } = 1_000;
}
@@ -0,0 +1,26 @@
<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.OpcUa</Title>
<Company>EonaCat</Company>
<PackageId>EonaCat.Connections.OpcUa</PackageId>
<Version>1.0.0</Version>
<Authors>Jeroen Saey</Authors>
<Description>OPC UA client and server for EonaCat.Connections</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections\EonaCat.Connections.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="2.0.1" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="2.0.1" />
</ItemGroup>
</Project>
@@ -0,0 +1,158 @@
using Opc.Ua;
using Opc.Ua.Configuration;
namespace EonaCat.Connections.OpcUa.Infrastructure;
internal static class OpcUaApplicationConfigurationFactory
{
public static async Task<ApplicationConfiguration> CreateClientAsync(
Configuration.OpcUaClientOptions options,
CancellationToken cancellationToken)
{
var configuration = CreateBase(
options.ApplicationName,
options.ApplicationUri,
ApplicationType.Client,
options.AutoAcceptUntrustedCertificates,
options.CheckCertificateRevocation,
options.OperationTimeoutMilliseconds);
configuration.ClientConfiguration = new ClientConfiguration
{
DefaultSessionTimeout = options.SessionTimeoutMilliseconds
};
await ValidateAndCreateCertificateAsync(configuration, cancellationToken).ConfigureAwait(false);
return configuration;
}
public static async Task<ApplicationConfiguration> CreateServerAsync(
Configuration.OpcUaServerOptions options,
CancellationToken cancellationToken)
{
var configuration = CreateBase(
options.ApplicationName,
options.ApplicationUri,
ApplicationType.Server,
options.AutoAcceptUntrustedCertificates,
options.CheckCertificateRevocation,
options.OperationTimeoutMilliseconds);
configuration.ServerConfiguration = new ServerConfiguration
{
BaseAddresses = new[] { options.BaseAddress },
SecurityPolicies = CreateSecurityPolicies(options),
UserTokenPolicies = new[]
{
new UserTokenPolicy(UserTokenType.Anonymous)
},
MaxSessionCount = options.MaxSessionCount,
MaxSubscriptionCount = options.MaxSubscriptionCount
};
await ValidateAndCreateCertificateAsync(configuration, cancellationToken).ConfigureAwait(false);
return configuration;
}
private static List<ServerSecurityPolicy> CreateSecurityPolicies(
Configuration.OpcUaServerOptions options)
{
var policies = new List<ServerSecurityPolicy>();
if (options.AllowUnsecuredEndpoint)
{
policies.Add(new ServerSecurityPolicy
{
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
});
}
if (options.EnableSecureEndpoint)
{
policies.Add(new ServerSecurityPolicy
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Basic256Sha256
});
}
if (policies.Count == 0)
{
throw new ArgumentException("At least one OPC UA endpoint security policy must be enabled.", nameof(options));
}
return policies;
}
private static ApplicationConfiguration CreateBase(
string applicationName,
string applicationUri,
ApplicationType applicationType,
bool autoAcceptUntrustedCertificates,
bool checkCertificateRevocation,
int operationTimeoutMilliseconds)
{
var certificateRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"EonaCat",
"OpcUa",
applicationType.ToString());
return new ApplicationConfiguration(OpcUaRuntime.Telemetry)
{
ApplicationName = applicationName,
ApplicationUri = applicationUri,
ApplicationType = applicationType,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = "Directory",
StorePath = Path.Combine(certificateRoot, "own"),
SubjectName = $"CN={applicationName}, DC={Utils.GetHostName()}"
},
TrustedPeerCertificates = CreateTrustList(certificateRoot, "trusted"),
TrustedIssuerCertificates = CreateTrustList(certificateRoot, "issuers"),
RejectedCertificateStore = new CertificateTrustList
{
StoreType = "Directory",
StorePath = Path.Combine(certificateRoot, "rejected")
},
AutoAcceptUntrustedCertificates = autoAcceptUntrustedCertificates,
RejectSHA1SignedCertificates = true,
MinimumCertificateKeySize = 2048,
RejectUnknownRevocationStatus = checkCertificateRevocation
},
TransportConfigurations = Array.Empty<TransportConfiguration>(),
TransportQuotas = new TransportQuotas
{
OperationTimeout = operationTimeoutMilliseconds
}
};
}
private static CertificateTrustList CreateTrustList(string root, string name) => new()
{
StoreType = "Directory",
StorePath = Path.Combine(root, name)
};
private static async Task ValidateAndCreateCertificateAsync(
ApplicationConfiguration configuration,
CancellationToken cancellationToken)
{
await configuration.ValidateAsync(configuration.ApplicationType, cancellationToken).ConfigureAwait(false);
var application = new ApplicationInstance(OpcUaRuntime.Telemetry)
{
ApplicationName = configuration.ApplicationName,
ApplicationType = configuration.ApplicationType,
ApplicationConfiguration = configuration
};
if (!await application.CheckApplicationInstanceCertificatesAsync(false, 2048, cancellationToken).ConfigureAwait(false))
{
throw new InvalidOperationException("OPC UA application certificate could not be created or validated.");
}
}
}
@@ -0,0 +1,12 @@
using Opc.Ua;
using Opc.Ua.Client;
namespace EonaCat.Connections.OpcUa.Infrastructure;
internal static class OpcUaRuntime
{
private static readonly ITelemetryContext TelemetryContext = DefaultTelemetry.Create(_ => { });
public static DefaultSessionFactory SessionFactory { get; } = new(TelemetryContext);
public static ITelemetryContext Telemetry => SessionFactory.Telemetry;
}
@@ -0,0 +1,7 @@
namespace EonaCat.Connections.OpcUa.Models;
public sealed class OpcUaConnectionEventArgs : EventArgs
{
public required string EndpointUrl { get; init; }
public string? SessionName { get; init; }
}
@@ -0,0 +1,13 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Models;
public sealed record OpcUaMethodArgument(string Name, NodeId DataType, string? Description = null);
public sealed record OpcUaMethodDefinition(
string Identifier,
string DisplayName,
IReadOnlyList<OpcUaMethodArgument> InputArguments,
IReadOnlyList<OpcUaMethodArgument> OutputArguments,
Func<IReadOnlyList<object?>, IReadOnlyList<object?>> Handler,
string? Description = null);
@@ -0,0 +1,11 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Models;
public sealed record OpcUaNodeDefinition(
string Identifier,
string DisplayName,
NodeId DataType,
object? InitialValue = null,
byte AccessLevel = AccessLevels.CurrentReadOrWrite,
string? Description = null);
@@ -0,0 +1,11 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Models;
public sealed class OpcUaValueChangedEventArgs : EventArgs
{
public required NodeId NodeId { get; init; }
public object? Value { get; init; }
public StatusCode StatusCode { get; init; }
public DateTime SourceTimestamp { get; init; }
}
@@ -0,0 +1,44 @@
using EonaCat.Connections.OpcUa.Infrastructure;
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Server;
namespace EonaCat.Connections.OpcUa.Server;
internal sealed class EonaCatOpcUaServer : StandardServer
{
private readonly string _namespaceUri;
private readonly IReadOnlyCollection<OpcUaNodeDefinition> _nodes;
private readonly IReadOnlyCollection<OpcUaMethodDefinition> _methods;
public EonaCatOpcUaServer(
string namespaceUri,
IReadOnlyCollection<OpcUaNodeDefinition> nodes,
IReadOnlyCollection<OpcUaMethodDefinition> methods)
: base(OpcUaRuntime.Telemetry)
{
_namespaceUri = namespaceUri;
_nodes = nodes;
_methods = methods;
}
public OpcUaAddressSpace? AddressSpace { get; private set; }
protected override MasterNodeManager CreateMasterNodeManager(
IServerInternal server,
ApplicationConfiguration configuration)
{
AddressSpace = new OpcUaAddressSpace(server, configuration, _namespaceUri, _nodes, _methods);
return new MasterNodeManager(server, configuration, null, AddressSpace);
}
protected override ServerProperties LoadServerProperties() => new()
{
ManufacturerName = "EonaCat",
ProductName = "EonaCat Generic OPC UA Server",
ProductUri = "urn:EonaCat:Connector:OpcUa",
SoftwareVersion = Utils.GetAssemblySoftwareVersion(),
BuildNumber = Utils.GetAssemblyBuildNumber(),
BuildDate = Utils.GetAssemblyTimestamp()
};
}
@@ -0,0 +1,197 @@
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Server;
using System.Collections.Concurrent;
namespace EonaCat.Connections.OpcUa.Server;
internal sealed class OpcUaAddressSpace : CustomNodeManager2
{
private readonly IReadOnlyCollection<OpcUaNodeDefinition> _nodeDefinitions;
private readonly IReadOnlyCollection<OpcUaMethodDefinition> _methodDefinitions;
private readonly ConcurrentDictionary<string, BaseDataVariableState> _variables = new(StringComparer.Ordinal);
public OpcUaAddressSpace(
IServerInternal server,
ApplicationConfiguration configuration,
string namespaceUri,
IReadOnlyCollection<OpcUaNodeDefinition> nodeDefinitions,
IReadOnlyCollection<OpcUaMethodDefinition> methodDefinitions)
: base(server, configuration, namespaceUri)
{
_nodeDefinitions = nodeDefinitions;
_methodDefinitions = methodDefinitions;
SystemContext.NodeIdFactory = this;
}
public event EventHandler<OpcUaValueChangedEventArgs>? ValueChanged;
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
{
lock (Lock)
{
if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out var references))
{
references = new List<IReference>();
externalReferences[ObjectIds.ObjectsFolder] = references;
}
var root = new FolderState(null)
{
NodeId = new NodeId("EonaCat", NamespaceIndex),
BrowseName = new QualifiedName("EonaCat", NamespaceIndex),
DisplayName = (LocalizedText)"EonaCat",
TypeDefinitionId = ObjectTypeIds.FolderType,
EventNotifier = EventNotifiers.None
};
root.AddReference(ReferenceTypeIds.Organizes, true, ObjectIds.ObjectsFolder);
references.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, root.NodeId));
foreach (var definition in _nodeDefinitions)
{
AddVariable(root, definition);
}
foreach (var definition in _methodDefinitions)
{
AddMethod(root, definition);
}
AddPredefinedNode(SystemContext, root);
}
}
public NodeId ResolveNodeId(string identifier) => new(identifier, NamespaceIndex);
public bool TrySetValue(string identifier, object? value)
{
if (!_variables.TryGetValue(identifier, out var variable))
{
return false;
}
lock (Lock)
{
variable.Value = new Variant(value);
variable.StatusCode = StatusCodes.Good;
variable.Timestamp = DateTime.UtcNow;
variable.ClearChangeMasks(SystemContext, false);
}
RaiseValueChanged(variable);
return true;
}
private void AddVariable(NodeState parent, OpcUaNodeDefinition definition)
{
var variable = new BaseDataVariableState(parent)
{
NodeId = ResolveNodeId(definition.Identifier),
BrowseName = new QualifiedName(definition.DisplayName, NamespaceIndex),
DisplayName = (LocalizedText)definition.DisplayName,
Description = (LocalizedText)definition.Description,
TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
ReferenceTypeId = ReferenceTypeIds.HasComponent,
DataType = definition.DataType,
ValueRank = ValueRanks.Scalar,
AccessLevel = definition.AccessLevel,
UserAccessLevel = definition.AccessLevel,
Historizing = false,
Value = new Variant(definition.InitialValue),
StatusCode = StatusCodes.Good,
Timestamp = DateTime.UtcNow
};
variable.OnSimpleWriteValue = HandleWrite;
parent.AddChild(variable);
_variables[definition.Identifier] = variable;
}
private void AddMethod(NodeState parent, OpcUaMethodDefinition definition)
{
var method = new MethodState(parent)
{
NodeId = ResolveNodeId(definition.Identifier),
BrowseName = new QualifiedName(definition.DisplayName, NamespaceIndex),
DisplayName = (LocalizedText)definition.DisplayName,
Description = (LocalizedText)definition.Description,
ReferenceTypeId = ReferenceTypeIds.HasComponent,
Executable = true,
UserExecutable = true
};
method.InputArguments = CreateArguments(method, "InputArguments", definition.InputArguments);
method.OutputArguments = CreateArguments(method, "OutputArguments", definition.OutputArguments);
method.OnCallMethod = (_, _, inputArguments, outputArguments) =>
{
try
{
var inputs = new object?[inputArguments.Count];
for (var index = 0; index < inputs.Length; index++)
{
inputs[index] = inputArguments[index].Value;
}
var results = definition.Handler(inputs);
for (var index = 0; index < Math.Min(results.Count, outputArguments.Count); index++)
{
outputArguments[index] = new Variant(results[index]);
}
return ServiceResult.Good;
}
catch (Exception exception)
{
return new ServiceResult(exception, StatusCodes.BadUnexpectedError);
}
};
parent.AddChild(method);
}
private PropertyState<ArrayOf<Argument>> CreateArguments(
NodeState parent,
string name,
IReadOnlyList<OpcUaMethodArgument> definitions)
{
var property = PropertyState<ArrayOf<Argument>>.With<StructureBuilder<Argument>>(parent);
property.NodeId = new NodeId($"{parent.NodeId.Identifier}.{name}", NamespaceIndex);
property.BrowseName = (QualifiedName)(name == "InputArguments" ? BrowseNames.InputArguments : BrowseNames.OutputArguments);
property.DisplayName = (LocalizedText)name;
property.TypeDefinitionId = VariableTypeIds.PropertyType;
property.ReferenceTypeId = ReferenceTypeIds.HasProperty;
property.DataType = DataTypeIds.Argument;
property.ValueRank = ValueRanks.OneDimension;
property.Value = definitions.Select(definition => new Argument
{
Name = definition.Name,
DataType = definition.DataType,
ValueRank = ValueRanks.Scalar,
Description = (LocalizedText)definition.Description
}).ToArray();
return property;
}
private ServiceResult HandleWrite(ISystemContext context, NodeState node, ref Variant value)
{
if (node is not BaseDataVariableState variable || (variable.AccessLevel & AccessLevels.CurrentWrite) == 0)
{
return StatusCodes.BadNotWritable;
}
variable.Value = value;
variable.Timestamp = DateTime.UtcNow;
variable.StatusCode = StatusCodes.Good;
RaiseValueChanged(variable);
return ServiceResult.Good;
}
private void RaiseValueChanged(BaseDataVariableState variable)
{
ValueChanged?.Invoke(this, new OpcUaValueChangedEventArgs
{
NodeId = variable.NodeId,
Value = variable.Value.Value,
StatusCode = variable.StatusCode,
SourceTimestamp = variable.Timestamp.ToDateTime()
});
}
}
@@ -0,0 +1,170 @@
using EonaCat.Connections.OpcUa.Configuration;
using EonaCat.Connections.OpcUa.Infrastructure;
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Configuration;
namespace EonaCat.Connections.OpcUa.Server;
public sealed class OpcUaNetworkServer : IAsyncDisposable, IDisposable
{
private readonly OpcUaServerOptions _options;
private readonly List<OpcUaNodeDefinition> _nodes = [];
private readonly List<OpcUaMethodDefinition> _methods = [];
private readonly SemaphoreSlim _lifecycleLock = new(1, 1);
private ApplicationInstance? _application;
private EonaCatOpcUaServer? _server;
private bool _disposed;
public OpcUaNetworkServer(OpcUaServerOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public bool IsStarted { get; private set; }
public string EndpointUrl => _options.BaseAddress;
public string NamespaceUri => _options.NamespaceUri;
public event EventHandler? Started;
public event EventHandler? Stopped;
public event EventHandler<OpcUaValueChangedEventArgs>? ValueChanged;
public event EventHandler<Exception>? Error;
public OpcUaNetworkServer AddVariable(OpcUaNodeDefinition definition)
{
EnsureNotStarted();
ArgumentNullException.ThrowIfNull(definition);
if (_nodes.Any(node => string.Equals(node.Identifier, definition.Identifier, StringComparison.Ordinal)))
{
throw new ArgumentException($"A node with identifier '{definition.Identifier}' is already registered.", nameof(definition));
}
_nodes.Add(definition);
return this;
}
public OpcUaNetworkServer AddMethod(OpcUaMethodDefinition definition)
{
EnsureNotStarted();
ArgumentNullException.ThrowIfNull(definition);
if (_methods.Any(method => string.Equals(method.Identifier, definition.Identifier, StringComparison.Ordinal)))
{
throw new ArgumentException($"A method with identifier '{definition.Identifier}' is already registered.", nameof(definition));
}
_methods.Add(definition);
return this;
}
public async Task StartAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (IsStarted)
{
return;
}
var configuration = await OpcUaApplicationConfigurationFactory
.CreateServerAsync(_options, cancellationToken)
.ConfigureAwait(false);
_server = new EonaCatOpcUaServer(_options.NamespaceUri, _nodes.ToArray(), _methods.ToArray());
_application = new ApplicationInstance(OpcUaRuntime.Telemetry)
{
ApplicationName = _options.ApplicationName,
ApplicationType = ApplicationType.Server,
ApplicationConfiguration = configuration
};
await _application.StartAsync(_server).ConfigureAwait(false);
if (_server.AddressSpace != null)
{
_server.AddressSpace.ValueChanged += HandleValueChanged;
}
IsStarted = true;
Started?.Invoke(this, EventArgs.Empty);
}
catch (Exception exception)
{
Error?.Invoke(this, exception);
throw;
}
finally
{
_lifecycleLock.Release();
}
}
public NodeId GetNodeId(string identifier)
{
ArgumentException.ThrowIfNullOrWhiteSpace(identifier);
return _server?.AddressSpace?.ResolveNodeId(identifier)
?? throw new InvalidOperationException("The OPC UA server has not started.");
}
public bool TrySetValue(string identifier, object? value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(identifier);
return _server?.AddressSpace?.TrySetValue(identifier, value) == true;
}
public async Task StopAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (!IsStarted)
{
return;
}
if (_server?.AddressSpace != null)
{
_server.AddressSpace.ValueChanged -= HandleValueChanged;
}
if (_application != null)
{
await _application.StopAsync().ConfigureAwait(false);
}
_server?.Dispose();
_server = null;
_application = null;
IsStarted = false;
Stopped?.Invoke(this, EventArgs.Empty);
}
finally
{
_lifecycleLock.Release();
}
}
private void HandleValueChanged(object? sender, OpcUaValueChangedEventArgs args) =>
ValueChanged?.Invoke(this, args);
private void EnsureNotStarted()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (IsStarted)
{
throw new InvalidOperationException("Nodes and methods must be registered before the OPC UA server starts.");
}
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
await StopAsync().ConfigureAwait(false);
_disposed = true;
_lifecycleLock.Dispose();
}
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.Quic\EonaCat.Connections.Quic.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,75 @@
using EonaCat.Connections.Models;
using System.Runtime.Versioning;
namespace EonaCat.Connections.Quic.Client.Example
{
[RequiresPreviewFeatures]
public class Program
{
private const string SERVER_IP = "127.0.0.1";
private const int SERVER_PORT = 8443;
public static async Task Main(string[] args)
{
var config = new Configuration
{
Host = SERVER_IP,
Port = SERVER_PORT,
IsSelfSignedEnabled = true,
EnableAutoReconnect = true,
ReconnectDelayInSeconds = 5,
};
await using var client = new QuicNetworkClient(config);
client.OnConnected += (sender, e) =>
{
Console.WriteLine($"[QUIC Client] Connected to {e.RemoteEndPoint}");
};
client.OnDataReceived += (sender, e) =>
{
Console.WriteLine($"[QUIC Client] Received: {e.StringData}");
};
client.OnDisconnected += (sender, e) =>
{
Console.WriteLine($"[QUIC Client] Disconnected: {e.Reason}");
};
client.OnGeneralError += (sender, e) =>
{
Console.WriteLine($"[QUIC Client] Error: {e.Message} - {e.Exception?.Message}");
};
Console.WriteLine("[QUIC Client] Connecting...");
var connected = await client.ConnectAsync();
if (!connected)
{
Console.WriteLine("[QUIC Client] Failed to connect. Press any key to exit.");
Console.ReadKey();
return;
}
await client.SendNicknameAsync("QuicTestClient");
while (true)
{
Console.Write("Enter message (or 'exit'): ");
var message = Console.ReadLine();
if (string.IsNullOrEmpty(message) || message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
await client.SendAsync(message);
}
await client.DisconnectAsync();
Console.WriteLine("[QUIC Client] Disconnected. Press any key to exit.");
Console.ReadKey();
}
}
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.Quic\EonaCat.Connections.Quic.csproj" />
</ItemGroup>
</Project>
+117
View File
@@ -0,0 +1,117 @@
using EonaCat.Connections.Models;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace EonaCat.Connections.Quic.Server.Example
{
[RequiresPreviewFeatures]
public class Program
{
private const string LISTEN_IP = "127.0.0.1";
private const int LISTEN_PORT = 8443;
public static async Task Main(string[] args)
{
using var certificate = GenerateSelfSignedCertificate();
var config = new Configuration
{
Host = LISTEN_IP,
Port = LISTEN_PORT,
Certificate = certificate,
IsSelfSignedEnabled = true,
};
using var server = new QuicNetworkServer(config);
server.OnConnected += (sender, e) =>
{
Console.WriteLine($"[QUIC Server] Client connected: {e.ClientId} from {e.RemoteEndPoint}");
};
server.OnDataReceived += async (sender, e) =>
{
Console.WriteLine($"[QUIC Server] Received from {e.Nickname ?? e.ClientId}: {e.StringData}");
if (sender is QuicNetworkServer srv)
{
await srv.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}");
}
};
server.OnDisconnected += (sender, e) =>
{
Console.WriteLine($"[QUIC Server] Client disconnected: {e.Nickname ?? e.ClientId} ({e.Reason})");
};
server.OnGeneralError += (sender, e) =>
{
Console.WriteLine($"[QUIC Server] Error: {e.Message} - {e.Exception?.Message}");
};
Console.WriteLine($"[QUIC Server] Starting on {LISTEN_IP}:{LISTEN_PORT}...");
await server.StartAsync();
Console.WriteLine("[QUIC Server] Started. Press 'q' to stop.");
while (true)
{
var key = Console.ReadKey(true);
if (key.KeyChar == 'q')
{
break;
}
if (key.KeyChar == 'b')
{
Console.Write("Broadcast message: ");
var msg = Console.ReadLine();
if (!string.IsNullOrEmpty(msg))
{
await server.BroadcastAsync(msg);
}
}
if (key.KeyChar == 'c')
{
var clients = server.GetClients();
Console.WriteLine($"[QUIC Server] Active connections: {server.ActiveConnections}");
foreach (var client in clients)
{
Console.WriteLine($" - {client.Value.Nickname} ({client.Key}) from {client.Value.RemoteEndPoint}");
}
}
}
Console.WriteLine("[QUIC Server] Stopping...");
await server.StopAsync();
Console.WriteLine("[QUIC Server] Stopped.");
}
private static X509Certificate2 GenerateSelfSignedCertificate()
{
using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var request = new CertificateRequest("CN=localhost", ecdsa, HashAlgorithmName.SHA256);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature,
critical: false));
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") },
critical: false));
var sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName("localhost");
sanBuilder.AddIpAddress(System.Net.IPAddress.Loopback);
request.CertificateExtensions.Add(sanBuilder.Build());
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(200));
return new X509Certificate2(certificate.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable);
}
}
}
@@ -0,0 +1,25 @@
<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.Quic</Title>
<Company>EonaCat</Company>
<Copyright>Jeroen Saey</Copyright>
<PackageId>EonaCat.Connections.Quic</PackageId>
<Version>1.0.0</Version>
<Authors>Jeroen Saey</Authors>
<Description>EonaCat.Connections.Quic for QUIC client/servers</Description>
</PropertyGroup>
<PropertyGroup>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections\EonaCat.Connections.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,37 @@
using System.Net;
using System.Net.Quic;
using System.Runtime.Versioning;
namespace EonaCat.Connections.Quic
{
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("macos")]
[RequiresPreviewFeatures]
public class QuicClientConnection
{
public string Id { get; set; } = string.Empty;
public QuicConnection? Connection { get; set; }
public QuicStream? Stream { get; set; }
public IPEndPoint? RemoteEndPoint { get; set; }
public SemaphoreSlim WriteLock { get; } = new(1, 1);
public DateTime ConnectedAt { get; set; }
public DateTime LastActive { get; set; }
public DateTime LastDataSent { get; set; }
public DateTime LastDataReceived { 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;
}
}
@@ -0,0 +1,554 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Models;
using EonaCat.Connections.ConnectionDiagnostics;
using EonaCat.Connections.Helpers;
using System.Buffers;
using System.Net;
using System.Net.Quic;
using System.Net.Security;
using System.Runtime.Versioning;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.Quic
{
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("macos")]
[RequiresPreviewFeatures]
public class QuicNetworkClient : IAsyncDisposable, IDisposable
{
public static event EventHandler<LogMessage> OnLog;
private readonly Configuration _config;
private QuicConnection? _connection;
private QuicStream? _stream;
private Task? _receiveTask;
private Task? _autoReconnectTask;
private CancellationTokenSource? _clientCts;
private CancellationTokenSource? _connectionCts;
private CancellationTokenSource? _autoReconnectSource;
private bool _disposed;
private bool _stopAutoReconnecting;
private bool _wasConnected;
private DisconnectReason _reason;
private readonly SemaphoreSlim _connectLock = new(1, 1);
private readonly SemaphoreSlim _streamWriteLock = new(1, 1);
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 DisconnectionTime { get; private set; }
public bool IsAutoConnectStarted => _autoReconnectTask != null && !_autoReconnectTask.IsCompleted;
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 int DEFAULT_STREAM_ERROR_CODE { get; set; } = 0;
public int DEFAULT_CLOSE_ERROR_CODE { get; set; } = 0;
public int MAX_INBOUND_BIDIRECTIONAL_STREAMS { get; set; } = 10;
public int MAX_INBOUND_UNIDIRECTIONAL_STREAMS { get; set; } = 10;
public string PROTOCOL_CONNECTION_NAME { get; set; } = "EonaCat-connector";
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 QuicNetworkClient(Configuration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_clientCts = new CancellationTokenSource();
}
public async Task<bool> ConnectAsync()
{
if (!QuicConnection.IsSupported)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Message = "QUIC is not supported on this platform."
},
nameof(OnGeneralError));
return false;
}
await _connectLock.WaitAsync().ConfigureAwait(false);
try
{
if (_clientCts == null || _clientCts.IsCancellationRequested)
{
_clientCts?.Dispose();
_clientCts = new CancellationTokenSource();
}
if (IsConnected)
{
return true;
}
_connectionCts?.Cancel();
_connectionCts?.Dispose();
_connectionCts = new CancellationTokenSource();
var clientOptions = new QuicClientConnectionOptions
{
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
DefaultStreamErrorCode = DEFAULT_STREAM_ERROR_CODE,
DefaultCloseErrorCode = DEFAULT_CLOSE_ERROR_CODE,
MaxInboundBidirectionalStreams = MAX_INBOUND_BIDIRECTIONAL_STREAMS,
MaxInboundUnidirectionalStreams = MAX_INBOUND_UNIDIRECTIONAL_STREAMS,
ClientAuthenticationOptions = new SslClientAuthenticationOptions
{
ApplicationProtocols = new List<SslApplicationProtocol>
{
new SslApplicationProtocol(PROTOCOL_CONNECTION_NAME)
},
RemoteCertificateValidationCallback = (sender, certificate, chain, errors) =>
{
if (_config.IsSelfSignedEnabled)
{
return true;
}
return errors == SslPolicyErrors.None;
}
}
};
_connection = await QuicConnection.ConnectAsync(clientOptions, _connectionCts.Token).ConfigureAwait(false);
_stream = await _connection.OpenOutboundStreamAsync(QuicStreamType.Bidirectional, _connectionCts.Token).ConfigureAwait(false);
IsConnected = true;
ConnectionTime = DateTime.UtcNow;
LastActive = DateTime.UtcNow;
_receiveTask = Task.Run(() => ReceiveLoopAsync(_connectionCts.Token), _connectionCts.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 = Nickname ?? "self",
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 = "QUIC connection error"
},
nameof(OnGeneralError));
return false;
}
finally
{
try
{
_connectLock.Release();
}
catch
{
}
}
}
private async Task ReceiveLoopAsync(CancellationToken token)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
try
{
while (!token.IsCancellationRequested && _stream != null)
{
int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
if (bytesRead == 0)
{
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
return;
}
LastActive = DateTime.UtcNow;
LastDataReceived = DateTime.UtcNow;
BytesReceived += bytesRead;
MessagesReceived++;
var data = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
HandlingHelpers.SafeInvokeEventHandler(
OnDataReceived,
this,
new DataReceivedEventArgs
{
ClientId = Nickname ?? "self",
Data = data,
RemoteEndPoint = _connection?.RemoteEndPoint as IPEndPoint,
Nickname = Nickname
},
nameof(OnDataReceived));
}
}
catch (OperationCanceledException)
{
}
catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted)
{
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
}
catch (Exception exception)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = exception,
Message = "Error receiving QUIC data"
},
nameof(OnGeneralError));
await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
public async Task<bool> SendAsync(byte[] data)
{
if (!IsConnected || _stream == null || data == null || data.Length == 0)
{
return false;
}
try
{
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
try
{
await _stream.WriteAsync(data, _connectionCts?.Token ?? CancellationToken.None).ConfigureAwait(false);
await _stream.FlushAsync(_connectionCts?.Token ?? CancellationToken.None).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
LastActive = DateTime.UtcNow;
LastDataSent = DateTime.UtcNow;
BytesSent += data.Length;
MessagesSent++;
return true;
}
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 SendNicknameAsync(string nickname)
{
Nickname = nickname;
if (IsConnected)
{
await SendAsync($"NICK:{nickname}").ConfigureAwait(false);
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
{
ClientId = nickname,
Nickname = nickname
});
}
}
public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null)
{
if (!IsConnected && _connection == null)
{
return;
}
IsConnected = false;
DisconnectionTime = DateTime.UtcNow;
_reason = reason;
_connectionCts?.Cancel();
try
{
if (_stream != null)
{
_stream.Abort(QuicAbortDirection.Both, 0);
await _stream.DisposeAsync().ConfigureAwait(false);
_stream = null;
}
}
catch
{
}
try
{
if (_connection != null)
{
await _connection.CloseAsync(0).ConfigureAwait(false);
await _connection.DisposeAsync().ConfigureAwait(false);
_connection = 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 = Nickname ?? "self",
Reason = determinedReason,
Exception = exception,
RemoteEndPoint = remoteEndPoint,
Initiator = initiator,
ReasonDetails = reasonDetails,
DiagnosticContext = diagnosticContext
};
try
{
var clientLogger = ConnectionLogManager.GetClientLogger();
var localEndPoint = _connection?.LocalEndPoint?.ToString() ?? "[Unknown]";
clientLogger.LogDisconnection(
Nickname ?? "self",
"[QUIC 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 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.Debug, Message = "QUIC auto-reconnect: attempting reconnection..." });
await ConnectAsync().ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"QUIC auto-reconnect error: {ex.Message}" });
}
}
}
public void StopAutoReconnect()
{
_stopAutoReconnecting = true;
_autoReconnectSource?.Cancel();
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
try
{
_clientCts?.Cancel();
_clientCts?.Dispose();
}
catch
{
}
try
{
_connectionCts?.Cancel();
_connectionCts?.Dispose();
}
catch
{
}
try
{
_autoReconnectSource?.Cancel();
_autoReconnectSource?.Dispose();
}
catch
{
}
try
{
_stream?.Dispose();
}
catch
{
}
_connectLock.Dispose();
_streamWriteLock.Dispose();
GC.SuppressFinalize(this);
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
try
{
_clientCts?.Cancel();
_clientCts?.Dispose();
}
catch
{
}
try
{
_connectionCts?.Cancel();
_connectionCts?.Dispose();
}
catch
{
}
try
{
_autoReconnectSource?.Cancel();
_autoReconnectSource?.Dispose();
}
catch
{
}
try
{
_stream?.Dispose();
}
catch
{
}
try
{
if (_connection is not null)
{
await _connection.DisposeAsync().ConfigureAwait(false);
}
}
catch
{
}
_connectLock.Dispose();
_streamWriteLock.Dispose();
GC.SuppressFinalize(this);
}
}
}
@@ -0,0 +1,634 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Models;
using EonaCat.Connections.ConnectionDiagnostics;
using EonaCat.Connections.Helpers;
using System.Buffers;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Quic;
using System.Net.Security;
using System.Runtime.Versioning;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.Quic
{
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("macos")]
[RequiresPreviewFeatures]
public class QuicNetworkServer : IDisposable
{
public static event EventHandler<LogMessage> OnLog;
public int DEFAULT_STREAM_ERROR_CODE { get; set; } = 0;
public int DEFAULT_CLOSE_ERROR_CODE { get; set; } = 0;
public int MAX_INBOUND_BIDIRECTIONAL_STREAMS { get; set; } = 10;
public int MAX_INBOUND_UNIDIRECTIONAL_STREAMS { get; set; } = 10;
public string PROTOCOL_CONNECTION_NAME { get; set; } = "EonaCat-connector";
private readonly Configuration _config;
private readonly Stats _stats;
private readonly ConcurrentDictionary<string, QuicClientConnection> _clients = new();
private QuicListener? _listener;
private CancellationTokenSource? _serverCts;
private Task? _acceptTask;
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 QuicNetworkServer(Configuration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_stats = new Stats { StartTime = DateTime.UtcNow };
if (_config.Certificate == null)
{
throw new ArgumentException("A TLS certificate is required for QUIC. Set Configuration.Certificate.", nameof(config));
}
}
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?.Connection != null)
{
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()
{
if (!QuicListener.IsSupported)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Message = "QUIC is not supported on this platform."
},
nameof(OnGeneralError));
return;
}
_serverCts?.Dispose();
_serverCts = new CancellationTokenSource();
var listenerOptions = new QuicListenerOptions
{
ListenEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
ApplicationProtocols = new List<SslApplicationProtocol>
{
new SslApplicationProtocol(PROTOCOL_CONNECTION_NAME)
},
ConnectionOptionsCallback = (connection, clientHello, token) =>
{
var serverOptions = new QuicServerConnectionOptions
{
DefaultStreamErrorCode = DEFAULT_STREAM_ERROR_CODE,
DefaultCloseErrorCode = DEFAULT_CLOSE_ERROR_CODE,
MaxInboundBidirectionalStreams = MAX_INBOUND_BIDIRECTIONAL_STREAMS,
MaxInboundUnidirectionalStreams = MAX_INBOUND_UNIDIRECTIONAL_STREAMS,
ServerAuthenticationOptions = new SslServerAuthenticationOptions
{
ApplicationProtocols = new List<SslApplicationProtocol>
{
new SslApplicationProtocol(PROTOCOL_CONNECTION_NAME)
},
ServerCertificateContext = SslStreamCertificateContext.Create(_config.Certificate, additionalCertificates: _config.AdditionalCertificates)
}
};
return ValueTask.FromResult(serverOptions);
}
};
_listener = await QuicListener.ListenAsync(listenerOptions, _serverCts.Token).ConfigureAwait(false);
_acceptTask = Task.Run(() => AcceptClientsAsync(_serverCts.Token), _serverCts.Token);
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"EonaCat QUIC server started on {_config.Host}:{_config.Port}" });
}
private async Task AcceptClientsAsync(CancellationToken token)
{
while (!token.IsCancellationRequested && _listener != null)
{
try
{
var connection = await _listener.AcceptConnectionAsync(token).ConfigureAwait(false);
if (!CanAcceptConnection())
{
_stats.IncrementDroppedConnections();
try
{
await connection.CloseAsync(0).ConfigureAwait(false);
await connection.DisposeAsync().ConfigureAwait(false);
}
catch
{
}
continue;
}
_ = Task.Run(() => HandleConnectionAsync(connection, token), token);
}
catch (OperationCanceledException)
{
break;
}
catch (QuicException ex) when (ex.QuicError == QuicError.OperationAborted)
{
break;
}
catch (Exception exception)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs
{
Exception = exception,
Message = "Error accepting QUIC connection"
});
}
}
}
private async Task HandleConnectionAsync(QuicConnection connection, CancellationToken token)
{
var clientId = Guid.NewGuid().ToString("N");
var remoteEndPoint = connection.RemoteEndPoint;
QuicStream? stream = null;
var clientConnection = new QuicClientConnection
{
Id = clientId,
Connection = connection,
RemoteEndPoint = remoteEndPoint,
ConnectedAt = DateTime.UtcNow
};
if (!_clients.TryAdd(clientId, clientConnection))
{
_stats.IncrementDroppedConnections();
try
{
await connection.CloseAsync(0).ConfigureAwait(false);
await connection.DisposeAsync().ConfigureAwait(false);
}
catch
{
}
return;
}
_stats.IncrementTotalConnections();
HandlingHelpers.SafeInvokeEventHandler(
OnConnected,
this,
new ConnectionEventArgs
{
ClientId = clientId,
RemoteEndPoint = remoteEndPoint
},
nameof(OnConnected));
byte[]? buffer = null;
try
{
stream = await connection.AcceptInboundStreamAsync(token).ConfigureAwait(false);
clientConnection.Stream = stream;
buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
while (!token.IsCancellationRequested)
{
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
if (bytesRead == 0)
{
break;
}
clientConnection.LastActive = DateTime.UtcNow;
clientConnection.LastDataReceived = DateTime.UtcNow;
clientConnection.BytesReceived += bytesRead;
clientConnection.MessagesReceived++;
_stats.AddBytesReceived(bytesRead);
_stats.IncrementMessagesReceived();
var data = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
var text = Encoding.UTF8.GetString(data);
if (text.StartsWith("NICK:", StringComparison.Ordinal))
{
clientConnection.Nickname = text.Substring(5);
continue;
}
HandlingHelpers.SafeInvokeEventHandler(
OnDataReceived,
this,
new DataReceivedEventArgs
{
ClientId = clientId,
Data = data,
RemoteEndPoint = remoteEndPoint,
Nickname = clientConnection.Nickname
},
nameof(OnDataReceived));
}
}
catch (OperationCanceledException)
{
}
catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted)
{
}
catch (Exception exception)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
ClientId = clientId,
Nickname = clientConnection.Nickname,
Exception = exception,
Message = "Error handling QUIC client"
},
nameof(OnGeneralError));
}
finally
{
if (buffer != null)
{
ArrayPool<byte>.Shared.Return(buffer);
}
_clients.TryRemove(clientId, out _);
try
{
if (stream != null)
{
stream.Abort(QuicAbortDirection.Both, 0);
await stream.DisposeAsync().ConfigureAwait(false);
}
}
catch
{
}
try
{
await connection.CloseAsync(0).ConfigureAwait(false);
await connection.DisposeAsync().ConfigureAwait(false);
}
catch
{
}
var initiator = DisconnectionDiagnostics.DetermineInitiator(DisconnectReason.RemoteClosed, null);
var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(DisconnectReason.RemoteClosed, null);
var diagnosticContext = new Dictionary<string, string>
{
{ "IsLocalInitiated", initiator == "Local" ? "true" : "false" }
};
var connectionEventArgs = new ConnectionEventArgs
{
ClientId = clientId,
Nickname = clientConnection.Nickname,
RemoteEndPoint = remoteEndPoint,
Reason = DisconnectReason.RemoteClosed,
Initiator = initiator,
ReasonDetails = reasonDetails,
DiagnosticContext = diagnosticContext
};
try
{
var serverLogger = ConnectionLogManager.GetServerLogger();
var localEndPoint = clientConnection.Connection?.LocalEndPoint?.ToString() ?? "[Unknown]";
serverLogger.LogDisconnection(
clientId,
clientConnection.Nickname,
remoteEndPoint?.ToString() ?? "[Unknown]",
localEndPoint,
DisconnectReason.RemoteClosed.ToString(),
initiator,
null,
diagnosticContext
);
}
catch (Exception logEx)
{
System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}");
}
HandlingHelpers.SafeInvokeEventHandler(
OnDisconnected,
this,
connectionEventArgs,
nameof(OnDisconnected));
}
}
public async Task<bool> SendToClientAsync(string clientId, byte[] data)
{
if (!_clients.TryGetValue(clientId, out var client) || client.Stream == null)
{
return false;
}
try
{
await client.WriteLock.WaitAsync().ConfigureAwait(false);
try
{
await client.Stream.WriteAsync(data).ConfigureAwait(false);
await client.Stream.FlushAsync().ConfigureAwait(false);
}
finally
{
client.WriteLock.Release();
}
client.LastActive = DateTime.UtcNow;
client.LastDataSent = DateTime.UtcNow;
client.BytesSent += data.Length;
client.MessagesSent++;
_stats.AddBytesSent(data.Length);
_stats.IncrementMessagesSent();
return true;
}
catch (Exception exception)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs
{
ClientId = clientId,
Nickname = client.Nickname,
Exception = exception,
Message = "Error sending data to QUIC client"
});
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)
{
if (data == null || data.Length == 0)
{
return false;
}
bool any = false;
foreach (var client in _clients)
{
if (await SendToClientAsync(client.Key, data).ConfigureAwait(false))
{
any = true;
}
}
return any;
}
public async Task<bool> BroadcastAsync(string message)
=> await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
public ConcurrentDictionary<string, QuicClientConnection> GetClients() => _clients;
public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.ServerShutdown)
{
if (!_clients.TryRemove(clientId, out var client))
{
return;
}
try
{
if (client.Stream != null)
{
client.Stream.Abort(QuicAbortDirection.Both, 0);
await client.Stream.DisposeAsync().ConfigureAwait(false);
}
}
catch
{
}
try
{
if (client.Connection != null)
{
await client.Connection.CloseAsync(0).ConfigureAwait(false);
await client.Connection.DisposeAsync().ConfigureAwait(false);
}
}
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 = client.Connection?.LocalEndPoint?.ToString() ?? "[Unknown]";
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));
}
public void Stop()
{
_serverCts?.Cancel();
try
{
if (_listener != null)
{
_listener.DisposeAsync().AsTask().Wait();
}
}
catch
{
}
_listener = null;
foreach (var client in _clients.Keys.ToList())
{
try
{
DisconnectClientAsync(client, DisconnectReason.ServerShutdown).Wait();
}
catch
{
}
}
_clients.Clear();
}
public async Task StopAsync()
{
_serverCts?.Cancel();
try
{
if (_listener != null)
{
await _listener.DisposeAsync().ConfigureAwait(false);
}
}
catch
{
}
_listener = null;
foreach (var client in _clients.Keys.ToList())
{
await DisconnectClientAsync(client, DisconnectReason.ServerShutdown).ConfigureAwait(false);
}
_clients.Clear();
if (_acceptTask != null)
{
try
{
await _acceptTask.ConfigureAwait(false);
}
catch
{
}
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
Stop();
_serverCts?.Dispose();
OnConnected = null;
OnDisconnected = null;
OnDataReceived = null;
OnGeneralError = null;
}
}
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.REST\EonaCat.Connections.REST.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,91 @@
using EonaCat.Connections.Models;
namespace EonaCat.Connections.REST.Client.Example
{
public class Program
{
private const string SERVER_IP = "127.0.0.1";
private const int SERVER_PORT = 5580;
private const int WEBHOOK_PORT = 5581;
public static async Task Main(string[] args)
{
var config = new Configuration
{
Host = SERVER_IP,
Port = SERVER_PORT,
IsSelfSignedEnabled = true,
EnableAutoReconnect = true,
ReconnectDelayInSeconds = 5,
};
await using var client = new RestNetworkClient(config);
client.OnConnected += (sender, e) =>
{
Console.WriteLine($"[REST Client] Connected to {e.RemoteEndPoint} (clientId: {e.ClientId})");
};
client.OnDataReceived += (sender, e) =>
{
Console.WriteLine($"[REST Client] Received: {e.StringData}");
};
client.OnDisconnected += (sender, e) =>
{
Console.WriteLine($"[REST Client] Disconnected: {e.Reason}");
};
client.OnGeneralError += (sender, e) =>
{
Console.WriteLine($"[REST Client] Error: {e.Message} - {e.Exception?.Message}");
};
Console.WriteLine("[REST Client] Connecting...");
var connected = await client.ConnectAsync();
if (!connected)
{
Console.WriteLine("[REST Client] Failed to connect. Press any key to exit.");
Console.ReadKey();
return;
}
await client.SendNicknameAsync("RestTestClient");
Console.WriteLine($"[REST Client] Starting webhook listener on port {WEBHOOK_PORT}...");
await client.StartWebhookListenerAsync(WEBHOOK_PORT);
await client.RegisterWebhookAsync();
Console.WriteLine("[REST Client] Webhook registered.");
Console.WriteLine("[REST Client] Commands: type a message to send, 'broadcast <msg>' to broadcast, 'exit' to quit.");
while (true)
{
Console.Write("> ");
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input) || input.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
if (input.StartsWith("broadcast ", StringComparison.OrdinalIgnoreCase))
{
var msg = input.Substring("broadcast ".Length);
await client.BroadcastAsync(msg);
Console.WriteLine("[REST Client] Broadcast sent.");
}
else
{
await client.SendAsync(input);
}
}
await client.StopWebhookListenerAsync();
await client.DisconnectAsync();
Console.WriteLine("[REST Client] Disconnected. Press any key to exit.");
Console.ReadKey();
}
}
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.REST\EonaCat.Connections.REST.csproj" />
</ItemGroup>
</Project>
+114
View File
@@ -0,0 +1,114 @@
using EonaCat.Connections.Models;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace EonaCat.Connections.REST.Server.Example
{
public class Program
{
private const string LISTEN_IP = "127.0.0.1";
private const int LISTEN_PORT = 5580;
public static async Task Main(string[] args)
{
using var certificate = GenerateSelfSignedCertificate();
var config = new Configuration
{
Host = LISTEN_IP,
Port = LISTEN_PORT,
Certificate = certificate,
IsSelfSignedEnabled = true,
};
using var server = new RestNetworkServer(config);
server.OnConnected += (sender, e) =>
{
Console.WriteLine($"[REST Server] Client connected: {e.ClientId} from {e.RemoteEndPoint}");
};
server.OnDataReceived += async (sender, e) =>
{
Console.WriteLine($"[REST Server] Received from {e.Nickname ?? e.ClientId}: {e.StringData}");
if (sender is RestNetworkServer srv)
{
await srv.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}");
}
};
server.OnDisconnected += (sender, e) =>
{
Console.WriteLine($"[REST Server] Client disconnected: {e.Nickname ?? e.ClientId} ({e.Reason})");
};
server.OnGeneralError += (sender, e) =>
{
Console.WriteLine($"[REST Server] Error: {e.Message} - {e.Exception?.Message}");
};
Console.WriteLine($"[REST Server] Starting on {LISTEN_IP}:{LISTEN_PORT}...");
await server.StartAsync();
Console.WriteLine("[REST Server] Started. Press 'q' to stop.");
while (true)
{
var key = Console.ReadKey(true);
if (key.KeyChar == 'q')
{
break;
}
if (key.KeyChar == 'b')
{
Console.Write("Broadcast message: ");
var msg = Console.ReadLine();
if (!string.IsNullOrEmpty(msg))
{
await server.BroadcastAsync(msg);
}
}
if (key.KeyChar == 'c')
{
var clients = server.GetClients();
Console.WriteLine($"[REST Server] Active connections: {server.ActiveConnections}");
foreach (var client in clients)
{
Console.WriteLine($" - {client.Value.Nickname} ({client.Key}) from {client.Value.RemoteEndPoint}" +
$"{(client.Value.WebhookUrl != null ? $" [webhook: {client.Value.WebhookUrl}]" : "")}");
}
}
}
Console.WriteLine("[REST Server] Stopping...");
await server.StopAsync();
Console.WriteLine("[REST Server] Stopped.");
}
private static X509Certificate2 GenerateSelfSignedCertificate()
{
using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var request = new CertificateRequest("CN=localhost", ecdsa, HashAlgorithmName.SHA256);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature,
critical: false));
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") },
critical: false));
var sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName("localhost");
sanBuilder.AddIpAddress(System.Net.IPAddress.Loopback);
request.CertificateExtensions.Add(sanBuilder.Build());
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(200));
return new X509Certificate2(certificate.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable);
}
}
}
@@ -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();
}
}
}
@@ -12,7 +12,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="EonaCat.Json" Version="2.2.3" />
<PackageReference Include="EonaCat.Json" Version="2.2.5" />
</ItemGroup>
<ItemGroup>
+162 -33
View File
@@ -1,23 +1,35 @@
using EonaCat.Connections.Models;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
namespace EonaCat.Connections.Server.Example
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class Program
{
private const bool IsHeartBeatEnabled = false;
private static NetworkServer _server;
private static TcpListener _tcpListener;
private static readonly object _tcpLock = new object();
public static bool WaitForMessage { get; private set; } = true;
public static bool WaitForMessage { get; private set; }
public static bool ToConsoleOnly { get; private set; } = true;
public static async Task Main(string[] args)
{
CreateServerAsync().ConfigureAwait(false);
await BroadCastLoopTest();
while (true)
{
await Task.Delay(1000).ConfigureAwait(false);
}
ConnectedClientsTest();
while (true)
{
var message = string.Empty;
@@ -27,6 +39,10 @@ namespace EonaCat.Connections.Server.Example
Console.Write("Enter message to send (or 'exit' to quit): ");
message = Console.ReadLine();
}
else
{
message = $"Server broadcast at {DateTime.Now:HH:mm:ss}";
}
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
@@ -45,48 +61,145 @@ namespace EonaCat.Connections.Server.Example
}
}
private static async Task BroadCastLoopTest()
{
long keepAliveCounter = 0;
while (true)
{
var message = $"KeepAlive Test {++keepAliveCounter}";
if (_server.GetClients().Any(c => c.Value.IsConnected))
{
Console.WriteLine($"Broadcasting: {message}");
await _server.BroadcastAsync(message).ConfigureAwait(false);
}
await Task.Delay(1000).ConfigureAwait(false);
}
}
private static void ConnectedClientsTest()
{
foreach (var client in _server.GetClients())
{
Console.WriteLine($"Connected Client: ID={client.Value.Id}, Nickname={client.Value.Nickname}, RemoteEndPoint={client.Value.RemoteEndPoint}, IsConnected={client.Value.IsConnected}");
}
while (true)
{
Console.WriteLine("Press 'c' to check connected clients, 'q' to quit.");
var key = Console.ReadKey(true);
if (key.KeyChar == 'c')
{
foreach (var client in _server.GetClients())
{
Console.WriteLine($"Connected Client: ID={client.Value.Id}, Nickname={client.Value.Nickname}, RemoteEndPoint={client.Value.RemoteEndPoint}, IsConnected={client.Value.IsConnected}");
}
Console.WriteLine("Total clients: " + _server.GetClients().Count);
Console.WriteLine("Total connected clients: " + _server.GetClients().Count(c => c.Value.IsConnected));
}
else if (key.KeyChar == 'q')
{
break;
}
}
}
private static async Task DanielTestServer()
{
lock (_tcpLock)
{
try
{
_tcpListener?.Stop();
_tcpListener?.Server?.Close();
}
catch (Exception)
{
}
_tcpListener = null;
}
lock (_tcpLock)
{
_tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1111);
_tcpListener.Start();
Console.WriteLine("Listener started");
}
while (true)
{
var client = await _tcpListener.AcceptTcpClientAsync();
if (client != null)
{
Console.WriteLine("DanielTestServer: Client connected.");
}
Console.ReadKey();
_tcpListener.Stop();
Console.WriteLine("DanielTestServer: Listener stopped.");
await DanielTestServer();
break;
}
}
private static async Task CreateServerAsync()
{
var config = new Configuration
{
Protocol = ProtocolType.TCP,
Protocol = Models.ProtocolType.TCP,
Host = "0.0.0.0",
Port = 1111,
EnableHealthApi = true,
HealthApiBindAddress = System.Net.IPAddress.Loopback,
Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null),
UseAesEncryption = false,
MaxConnections = 100000,
AesPassword = "EonaCat.Connections.Password",
//Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("server.pfx", "p@ss"),
EnableHeartbeat = IsHeartBeatEnabled
AesPassword = "itudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tincidunt sollicitudin posuere. Phasellus tincidunt sollicitudin posuere. Nam tristique feugiat est vitae mollis.\",\"version\": 8.39},{\"name\": \"Bhupesh Menon\",\"language\": \"Hindi\",\"id\": \"0CEPNRDV98KT3ORP\",\"bio\": \"Maecenas tempus neque ut porttitor malesuada. Phasellus massa ligula, hendrerit eget efficitur eget, tincidunt in ligula. Quisque mauris ligula, efficitur porttitor sodales ac, lacinia non ex. Maecenas quis nisi nunc.\",\"version\": 2.69},{\"name\": \"Rohini Vasav\",\"language\": \"Hindi\",\"id\": \"UEFML43TCGS04KWM\",\"bio\": \"Ut accumsan, est vel fringilla varius, purus augue blandit nisl, eu rhoncus ligula purus vel dolor. Ut maximus, libero nec facilisis fringilla, ex sem sollicitudin leo, non congue tortor ligula in eros. Nam rutrum sollicitudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tinc",
EnableHeartbeat = IsHeartBeatEnabled,
EnableConnectionDebugLogs = true,
};
_server = new NetworkServer(config);
// Subscribe to events
_server.OnConnected += (sender, e) =>
{
WriteToLog($"Client {e.ClientId} connected from {e.RemoteEndPoint}");
Console.WriteLine($"New connection from {e.RemoteEndPoint} with Client ID: {e.ClientId}");
};
_server.OnConnectedWithNickname += (sender, e) => WriteToLog($"Client {e.ClientId} connected with nickname: {e.Nickname}");
_server.OnDataReceived += async (sender, e) =>
{
WriteToLog($"Received from {e.ClientId} ({e.RemoteEndPoint.ToString()}): {(e.IsBinary ? $"{e.Data.Length} bytes" : "a message")}");
// Echo back the message
if (e.IsBinary)
{
await _server.SendToClientAsync(e.ClientId, e.Data);
}
else
{
await _server.SendToClientAsync(e.ClientId, e.StringData);
}
};
_server.OnDisconnected += (sender, e) =>
{
WriteToLog($"Client {e.ClientId} disconnected from {e.RemoteEndPoint}");
Console.WriteLine($"Connection terminated from {e.RemoteEndPoint} with Client ID: {e.ClientId}");
Console.WriteLine($" → Reason: {e.Reason}");
Console.WriteLine($" → Initiated By: {e.Initiator}");
Console.WriteLine($" → Details: {e.ReasonDetails}");
if (e.ConnectionDuration.HasValue)
{
Console.WriteLine($" → Duration: {e.ConnectionDuration.Value.TotalSeconds:F2}s");
}
if (e.HasException)
{
Console.WriteLine($" → Exception: {e.Exception.GetType().Name}: {e.Exception.Message}");
}
if (e.DiagnosticContext != null && e.DiagnosticContext.Count > 0)
{
Console.WriteLine($" → Diagnostic Context:");
foreach (var kvp in e.DiagnosticContext)
{
Console.WriteLine($" {kvp.Key}: {kvp.Value}");
}
}
var message = string.Empty;
if (e.Reason == DisconnectReason.LocalClosed)
{
@@ -103,17 +216,33 @@ namespace EonaCat.Connections.Server.Example
{
if (e.Exception != null)
{
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Exception: {e.Exception.Message}";
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Initiator: {e.Initiator}. Exception: {e.Exception.Message}";
}
else
{
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}";
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Initiator: {e.Initiator}";
}
}
WriteToLog(message);
Console.WriteLine(message);
};
_server.OnConnectedWithNickname += (sender, e) => WriteToLog($"Client {e.ClientId} connected with nickname: {e.Nickname}");
_server.OnDataReceived += async (sender, e) =>
{
WriteToLog($"Received from {e.ClientId} ({e.Nickname ?? "NoNickname"}) ({e.RemoteEndPoint.ToString()}): {(e.IsBinary ? $"{e.Data.Length} bytes" : "a message")}");
if (e.IsBinary)
{
await _server.SendToClientAsync(e.ClientId, e.Data);
}
else
{
await _server.SendToClientAsync(e.ClientId, e.StringData);
}
};
_ = _server.StartAsync();
}
@@ -137,7 +266,7 @@ namespace EonaCat.Connections.Server.Example
return;
}
if (new FileInfo(logFilePath).Length > 5 * 1024 * 1024) // 5 MB
if (new FileInfo(logFilePath).Length > 5 * 1024 * 1024)
{
var archiveFilePath = Path.Combine(Path.GetDirectoryName(logFilePath) ?? ".", $"server_log{DateTime.Now:yyyyMMdd_HHmmss}.txt");
File.Move(logFilePath, archiveFilePath);
@@ -147,9 +276,9 @@ namespace EonaCat.Connections.Server.Example
File.AppendAllText(logFilePath, logMessage);
}
catch
catch (Exception)
{
// Ignore logging errors
}
}
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.gRPC\EonaCat.Connections.gRPC.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,73 @@
using EonaCat.Connections.Models;
namespace EonaCat.Connections.gRPC.Client.Example
{
public class Program
{
private const string SERVER_IP = "127.0.0.1";
private const int SERVER_PORT = 5443;
public static async Task Main(string[] args)
{
var config = new Configuration
{
Host = SERVER_IP,
Port = SERVER_PORT,
IsSelfSignedEnabled = true,
EnableAutoReconnect = true,
ReconnectDelayInSeconds = 5,
};
await using var client = new GrpcNetworkClient(config);
client.OnConnected += (sender, e) =>
{
Console.WriteLine($"[gRPC Client] Connected to {e.RemoteEndPoint}");
};
client.OnDataReceived += (sender, e) =>
{
Console.WriteLine($"[gRPC Client] Received: {e.StringData}");
};
client.OnDisconnected += (sender, e) =>
{
Console.WriteLine($"[gRPC Client] Disconnected: {e.Reason}");
};
client.OnGeneralError += (sender, e) =>
{
Console.WriteLine($"[gRPC Client] Error: {e.Message} - {e.Exception?.Message}");
};
Console.WriteLine("[gRPC Client] Connecting...");
var connected = await client.ConnectAsync();
if (!connected)
{
Console.WriteLine("[gRPC Client] Failed to connect. Press any key to exit.");
Console.ReadKey();
return;
}
await client.SendNicknameAsync("GrpcTestClient");
while (true)
{
Console.Write("Enter message (or 'exit'): ");
var message = Console.ReadLine();
if (string.IsNullOrEmpty(message) || message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
await client.SendAsync(message);
}
await client.DisconnectAsync();
Console.WriteLine("[gRPC Client] Disconnected. Press any key to exit.");
Console.ReadKey();
}
}
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections.gRPC\EonaCat.Connections.gRPC.csproj" />
</ItemGroup>
</Project>
+115
View File
@@ -0,0 +1,115 @@
using EonaCat.Connections.Models;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace EonaCat.Connections.gRPC.Server.Example
{
public class Program
{
private const string LISTEN_IP = "127.0.0.1";
private const int LISTEN_PORT = 5443;
public static async Task Main(string[] args)
{
using var certificate = GenerateSelfSignedCertificate();
var config = new Configuration
{
Host = LISTEN_IP,
Port = LISTEN_PORT,
Certificate = certificate,
IsSelfSignedEnabled = true,
};
using var server = new GrpcNetworkServer(config);
server.OnConnected += (sender, e) =>
{
Console.WriteLine($"[gRPC Server] Client connected: {e.ClientId} from {e.RemoteEndPoint}");
};
server.OnDataReceived += async (sender, e) =>
{
Console.WriteLine($"[gRPC Server] Received from {e.Nickname ?? e.ClientId}: {e.StringData}");
if (sender is GrpcNetworkServer srv)
{
await srv.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}");
}
};
server.OnDisconnected += (sender, e) =>
{
Console.WriteLine($"[gRPC Server] Client disconnected: {e.Nickname ?? e.ClientId} ({e.Reason})");
};
server.OnGeneralError += (sender, e) =>
{
Console.WriteLine($"[gRPC Server] Error: {e.Message} - {e.Exception?.Message}");
};
Console.WriteLine($"[gRPC Server] Starting on {LISTEN_IP}:{LISTEN_PORT}...");
await server.StartAsync();
Console.WriteLine("[gRPC Server] Started. Press 'q' to stop.");
while (true)
{
var key = Console.ReadKey(true);
if (key.KeyChar == 'q')
{
break;
}
if (key.KeyChar == 'b')
{
Console.Write("Broadcast message: ");
var msg = Console.ReadLine();
if (!string.IsNullOrEmpty(msg))
{
await server.BroadcastAsync(msg);
}
}
if (key.KeyChar == 'c')
{
var clients = server.GetClients();
Console.WriteLine($"[gRPC Server] Active connections: {server.ActiveConnections}");
foreach (var client in clients)
{
Console.WriteLine($" - {client.Value.Nickname} ({client.Key}) from {client.Value.RemoteEndPoint}");
}
}
}
Console.WriteLine("[gRPC Server] Stopping...");
await server.StopAsync();
Console.WriteLine("[gRPC Server] Stopped.");
}
private static X509Certificate2 GenerateSelfSignedCertificate()
{
using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var request = new CertificateRequest("CN=localhost", ecdsa, HashAlgorithmName.SHA256);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature,
critical: false));
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") },
critical: false));
var sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName("localhost");
sanBuilder.AddIpAddress(System.Net.IPAddress.Loopback);
request.CertificateExtensions.Add(sanBuilder.Build());
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(200));
return new X509Certificate2(certificate.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable);
}
}
}
@@ -0,0 +1,163 @@
using Grpc.Core;
using EonaCat.Connections;
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.gRPC.Proto;
using System.Net;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.gRPC
{
internal class ConnectorServiceImplementation : ConnectorService.ConnectorServiceBase
{
private readonly GrpcNetworkServer _server;
public ConnectorServiceImplementation(GrpcNetworkServer server)
{
_server = server;
}
public override async Task Connect(
IAsyncStreamReader<ConnectorMessage> requestStream,
IServerStreamWriter<ConnectorMessage> responseStream,
ServerCallContext context)
{
if (!_server.CanAcceptConnection())
{
_server.IncrementDroppedConnection();
throw new RpcException(new Status(StatusCode.ResourceExhausted, "Max connections reached"));
}
var clientId = Guid.NewGuid().ToString("N");
IPEndPoint? remoteEndPoint = null;
var httpContext = context.GetHttpContext();
if (httpContext?.Connection.RemoteIpAddress != null)
{
remoteEndPoint = new IPEndPoint(
httpContext.Connection.RemoteIpAddress,
httpContext.Connection.RemotePort);
}
var clientCts = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);
var clientConnection = new GrpcClientConnection
{
Id = clientId,
ResponseStream = responseStream,
RemoteEndPoint = remoteEndPoint,
ConnectedAt = DateTime.UtcNow,
CancellationSource = clientCts
};
if (!_server.AddClient(clientId, clientConnection))
{
clientCts.Dispose();
throw new RpcException(new Status(StatusCode.Aborted, "Failed to register client connection"));
}
_server.RaiseOnConnected(new ConnectionEventArgs
{
ClientId = clientId,
RemoteEndPoint = remoteEndPoint
});
try
{
while (await requestStream.MoveNext(clientCts.Token).ConfigureAwait(false))
{
if (clientCts.Token.IsCancellationRequested)
{
break;
}
var message = requestStream.Current;
clientConnection.LastActive = DateTime.UtcNow;
switch (message.Type)
{
case MessageType.Nickname:
clientConnection.Nickname = message.Text;
continue;
case MessageType.Pong:
_server.HandlePongReceived(clientId);
continue;
case MessageType.Ping:
await clientConnection.WriteLock.WaitAsync(clientCts.Token).ConfigureAwait(false);
try
{
var pongMsg = new ConnectorMessage { Type = MessageType.Pong };
await responseStream.WriteAsync(pongMsg).ConfigureAwait(false);
}
finally
{
clientConnection.WriteLock.Release();
}
continue;
case MessageType.Disconnect:
break;
case MessageType.Data:
default:
break;
}
if (message.Type == MessageType.Disconnect)
{
break;
}
clientConnection.LastDataReceived = DateTime.UtcNow;
var data = message.Data.ToByteArray();
clientConnection.BytesReceived += data.Length;
clientConnection.MessagesReceived++;
_server.TrackBytesReceived(data.Length);
_server.RaiseOnDataReceived(new DataReceivedEventArgs
{
ClientId = clientId,
Data = data,
RemoteEndPoint = remoteEndPoint,
Nickname = clientConnection.Nickname
});
}
}
catch (OperationCanceledException)
{
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
}
catch (Exception exception)
{
_server.RaiseOnGeneralError(new ErrorEventArgs
{
ClientId = clientId,
Nickname = clientConnection.Nickname,
Exception = exception,
Message = "Error handling gRPC client"
});
}
finally
{
if (_server.RemoveClient(clientId, out _))
{
_server.RaiseOnDisconnected(new ConnectionEventArgs
{
ClientId = clientId,
Nickname = clientConnection.Nickname,
RemoteEndPoint = remoteEndPoint,
Reason = DisconnectReason.RemoteClosed
});
}
clientCts.Dispose();
}
}
}
}
@@ -0,0 +1,35 @@
<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.gRPC</Title>
<Company>EonaCat</Company>
<Copyright>Jeroen Saey</Copyright>
<PackageId>EonaCat.Connections.gRPC</PackageId>
<Version>1.0.0</Version>
<Authors>Jeroen Saey</Authors>
<Description>EonaCat.Connections.gRPC for gRPC client/servers with optional TLS 1.2</Description>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="Protos\connector.proto" GrpcServices="Both" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections\EonaCat.Connections.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.85.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.85.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,77 @@
using Grpc.Net.Client;
using EonaCat.Connections.Models;
using System.Net.Security;
using System.Security.Authentication;
namespace EonaCat.Connections.gRPC
{
public static class GrpcChannelFactory
{
public static GrpcChannel Create(Configuration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
var scheme = config.UseSsl ? "https" : "http";
var address = $"{scheme}://{config.Host}:{config.Port}";
return Create(address, config);
}
public static GrpcChannel Create(string address, Configuration config)
{
if (string.IsNullOrWhiteSpace(address))
{
throw new ArgumentNullException(nameof(address));
}
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
return GrpcChannel.ForAddress(address, BuildChannelOptions(config));
}
public static GrpcChannelOptions BuildChannelOptions(Configuration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
var options = new GrpcChannelOptions();
if (config.UseSsl)
{
options.HttpHandler = new SocketsHttpHandler
{
SslOptions = new SslClientAuthenticationOptions
{
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
RemoteCertificateValidationCallback = (sender, certificate, chain, errors) =>
{
if (config.IsSelfSignedEnabled)
{
return true;
}
return errors == SslPolicyErrors.None;
}
}
};
}
else
{
options.HttpHandler = new SocketsHttpHandler
{
EnableMultipleHttp2Connections = true
};
}
return options;
}
}
}
@@ -0,0 +1,40 @@
using Grpc.Core;
using EonaCat.Connections.gRPC.Proto;
using System.Net;
namespace EonaCat.Connections.gRPC
{
public class GrpcClientConnection
{
public string Id { get; set; } = string.Empty;
public IServerStreamWriter<ConnectorMessage>? ResponseStream { get; set; }
public IPEndPoint? RemoteEndPoint { get; set; }
public SemaphoreSlim WriteLock { get; } = new(1, 1);
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; }
public bool IsConnected => CancellationSource != null && !CancellationSource.IsCancellationRequested;
public TimeSpan ConnectedTime() => DateTime.UtcNow - ConnectedAt;
public TimeSpan IdleTime() => DateTime.UtcNow - (LastActive == default ? ConnectedAt : LastActive);
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;
}
}
@@ -0,0 +1,599 @@
using Google.Protobuf;
using Grpc.Core;
using Grpc.Net.Client;
using EonaCat.Connections;
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using EonaCat.Connections.gRPC.Proto;
using System.Net;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.gRPC
{
public class GrpcNetworkClient : IAsyncDisposable, IDisposable
{
public static event EventHandler<LogMessage> OnLog;
private readonly Configuration _config;
private GrpcChannel? _channel;
private AsyncDuplexStreamingCall<ConnectorMessage, ConnectorMessage>? _call;
private Task? _receiveTask;
private Task? _autoReconnectTask;
private Task? _pingTask;
private CancellationTokenSource? _clientCts;
private CancellationTokenSource? _connectionCts;
private CancellationTokenSource? _autoReconnectSource;
private bool _disposed;
private bool _stopAutoReconnecting;
private bool _wasConnected;
private DisconnectReason _reason;
private readonly SemaphoreSlim _connectLock = new(1, 1);
private readonly SemaphoreSlim _streamWriteLock = new(1, 1);
public GrpcChannel? Channel => _channel;
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 DisconnectionTime { get; private set; }
public DateTime LastPingSent { get; private set; }
public DateTime LastPongReceived { get; private set; }
public bool IsAutoConnectStarted => _autoReconnectTask != null && !_autoReconnectTask.IsCompleted;
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 HealthApiServer HealthApi { get; }
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>? OnPingReceived;
public event EventHandler<PingEventArgs>? OnPongReceived;
public GrpcNetworkClient(Configuration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_clientCts = new CancellationTokenSource();
HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson);
}
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;
}
_connectionCts?.Cancel();
_connectionCts?.Dispose();
_connectionCts = new CancellationTokenSource();
var scheme = _config.UseSsl ? "https" : "http";
var address = $"{scheme}://{_config.Host}:{_config.Port}";
_channel = GrpcChannelFactory.Create(address, _config);
var client = new ConnectorService.ConnectorServiceClient(_channel);
_call = client.Connect(cancellationToken: _connectionCts.Token);
IsConnected = true;
ConnectionTime = DateTime.UtcNow;
LastActive = DateTime.UtcNow;
_receiveTask = Task.Run(() => ReceiveLoopAsync(_connectionCts.Token), _connectionCts.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);
}
if (_config.EnableHeartbeat)
{
_pingTask = Task.Run(() => PingLoopAsync(_connectionCts.Token), _connectionCts.Token);
}
if (_config.EnableHealthApi)
{
HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress);
}
_wasConnected = true;
HandlingHelpers.SafeInvokeEventHandler(
OnConnected,
this,
new ConnectionEventArgs
{
ClientId = Nickname ?? "self",
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 = "gRPC connection error"
},
nameof(OnGeneralError));
return false;
}
finally
{
try
{
_connectLock.Release();
}
catch
{
}
}
}
private async Task ReceiveLoopAsync(CancellationToken token)
{
try
{
if (_call == null)
{
return;
}
while (await _call.ResponseStream.MoveNext(token).ConfigureAwait(false))
{
if (token.IsCancellationRequested)
{
break;
}
var message = _call.ResponseStream.Current;
LastActive = DateTime.UtcNow;
switch (message.Type)
{
case MessageType.Ping:
OnPingReceived?.Invoke(this, new PingEventArgs
{
Id = Nickname ?? "self",
ReceivedTime = DateTime.UtcNow
});
await SendPongAsync().ConfigureAwait(false);
continue;
case MessageType.Pong:
LastPongReceived = DateTime.UtcNow;
OnPongReceived?.Invoke(this, new PingEventArgs
{
Id = Nickname ?? "self",
ReceivedTime = DateTime.UtcNow
});
continue;
case MessageType.Disconnect:
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
return;
case MessageType.Data:
default:
break;
}
LastDataReceived = DateTime.UtcNow;
var data = message.Data.ToByteArray();
BytesReceived += data.Length;
MessagesReceived++;
HandlingHelpers.SafeInvokeEventHandler(
OnDataReceived,
this,
new DataReceivedEventArgs
{
ClientId = Nickname ?? "self",
Data = data,
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
Nickname = Nickname
},
nameof(OnDataReceived));
}
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
}
catch (Exception exception)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = exception,
Message = "Error receiving gRPC data"
},
nameof(OnGeneralError));
await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false);
}
}
private async Task PingLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false);
if (IsConnected && _call != null)
{
await _streamWriteLock.WaitAsync(token).ConfigureAwait(false);
try
{
var pingMsg = new ConnectorMessage { Type = MessageType.Ping };
await _call.RequestStream.WriteAsync(pingMsg).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
LastPingSent = DateTime.UtcNow;
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"gRPC ping loop error: {ex.Message}" });
}
}
}
private async Task SendPongAsync()
{
if (!IsConnected || _call == null)
{
return;
}
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
try
{
var pongMsg = new ConnectorMessage { Type = MessageType.Pong };
await _call.RequestStream.WriteAsync(pongMsg).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
}
public async Task<bool> SendAsync(byte[] data)
{
if (!IsConnected || _call == null || data == null || data.Length == 0)
{
return false;
}
try
{
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
try
{
var message = new ConnectorMessage
{
Type = MessageType.Data,
Data = ByteString.CopyFrom(data)
};
await _call.RequestStream.WriteAsync(message).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
LastActive = DateTime.UtcNow;
LastDataSent = DateTime.UtcNow;
BytesSent += data.Length;
MessagesSent++;
return true;
}
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 SendNicknameAsync(string nickname)
{
Nickname = nickname;
if (IsConnected && _call != null)
{
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
try
{
var message = new ConnectorMessage
{
Type = MessageType.Nickname,
Text = nickname
};
await _call.RequestStream.WriteAsync(message).ConfigureAwait(false);
}
finally
{
_streamWriteLock.Release();
}
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
{
ClientId = nickname,
Nickname = nickname
});
}
}
public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null)
{
if (!IsConnected && _channel == null)
{
return;
}
IsConnected = false;
DisconnectionTime = DateTime.UtcNow;
_reason = reason;
_connectionCts?.Cancel();
try
{
if (_call != null)
{
await _call.RequestStream.CompleteAsync().ConfigureAwait(false);
_call.Dispose();
_call = null;
}
}
catch
{
}
try
{
if (_channel != null)
{
_channel.Dispose();
_channel = null;
}
}
catch
{
}
HealthApi.Stop();
HandlingHelpers.SafeInvokeEventHandler(
OnDisconnected,
this,
new ConnectionEventArgs
{
ClientId = Nickname ?? "self",
Reason = reason,
Exception = exception,
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
},
nameof(OnDisconnected));
}
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.Debug, Message = "gRPC auto-reconnect: attempting reconnection..." });
await ConnectAsync().ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"gRPC auto-reconnect error: {ex.Message}" });
}
}
}
public void StopAutoReconnect()
{
_stopAutoReconnecting = true;
_autoReconnectSource?.Cancel();
}
public TClient CreateClient<TClient>(Func<GrpcChannel, TClient> factory)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
if (_channel == null)
{
throw new InvalidOperationException("Not connected. Call ConnectAsync first.");
}
return factory(_channel);
}
private string BuildHealthJson()
{
var E = HealthApiServer.JsonEscape;
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"grpc-client\"," +
$"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"isConnected\":{(IsConnected ? "true" : "false")}," +
$"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," +
$"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}" +
"}";
}
private string BuildStatusJson()
{
var E = HealthApiServer.JsonEscape;
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"grpc-client\"," +
$"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"isConnected\":{(IsConnected ? "true" : "false")}," +
$"\"nickname\":{E(Nickname ?? "self")}," +
$"\"bytesSent\":{BytesSent}," +
$"\"bytesReceived\":{BytesReceived}," +
$"\"messagesSent\":{MessagesSent}," +
$"\"messagesReceived\":{MessagesReceived}," +
$"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," +
$"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}," +
$"\"lastDataSentUtc\":{(LastDataSent == default ? "null" : E(LastDataSent.ToString("O")))}," +
$"\"lastDataReceivedUtc\":{(LastDataReceived == default ? "null" : E(LastDataReceived.ToString("O")))}" +
"}";
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_clientCts?.Cancel();
_clientCts?.Dispose();
_connectionCts?.Cancel();
_connectionCts?.Dispose();
_autoReconnectSource?.Cancel();
_autoReconnectSource?.Dispose();
HealthApi.Stop();
try
{
_call?.Dispose();
}
catch
{
}
try
{
_channel?.Dispose();
}
catch
{
}
_connectLock.Dispose();
_streamWriteLock.Dispose();
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
_clientCts?.Cancel();
_clientCts?.Dispose();
_connectionCts?.Cancel();
_connectionCts?.Dispose();
_autoReconnectSource?.Cancel();
_autoReconnectSource?.Dispose();
HealthApi.Stop();
try
{
_call?.Dispose();
}
catch
{
}
try
{
_channel?.Dispose();
}
catch
{
}
_connectLock.Dispose();
_streamWriteLock.Dispose();
}
}
}
@@ -0,0 +1,698 @@
using EonaCat.Connections;
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using EonaCat.Connections.gRPC.Proto;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Authentication;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.gRPC
{
public class GrpcNetworkServer : IDisposable, IAsyncDisposable
{
public static event EventHandler<LogMessage> OnLog;
private readonly Configuration _config;
private readonly Stats _stats;
private readonly ConcurrentDictionary<string, GrpcClientConnection> _clients = new();
private readonly ConcurrentDictionary<string, DateTime> _lastPingTimes = new();
private WebApplication? _app;
private CancellationTokenSource? _serverCts;
private Task? _serverTask;
private Task? _pingTask;
private Task? _pongTask;
private Task? _idleTask;
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 HealthApiServer HealthApi { get; }
public event EventHandler<ConnectionEventArgs>? OnConnected;
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
public event EventHandler<ErrorEventArgs>? OnGeneralError;
public event EventHandler<PingEventArgs>? OnClientPingResponse;
public event EventHandler<PingEventArgs>? OnPongMissed;
public GrpcNetworkServer(Configuration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_stats = new Stats { StartTime = DateTime.UtcNow };
HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson);
}
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?.IsConnected == true)
{
activeCount++;
}
}
return activeCount;
}
internal 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.Services.AddSingleton(this);
builder.Services.AddGrpc(options =>
{
options.MaxReceiveMessageSize = _config.MAX_MESSAGE_SIZE;
options.MaxSendMessageSize = _config.MAX_MESSAGE_SIZE;
});
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.Http2;
});
});
_app = builder.Build();
_app.MapGrpcService<ConnectorServiceImplementation>();
_serverTask = _app.RunAsync(_serverCts.Token);
if (_config.EnableHeartbeat)
{
_pingTask = Task.Run(() => PingLoopAsync(_serverCts.Token), _serverCts.Token);
_pongTask = Task.Run(() => PongMonitorLoopAsync(_serverCts.Token), _serverCts.Token);
}
if (_config.EnableHealthApi)
{
HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress);
}
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"EonaCat gRPC server started on {_config.Host}:{_config.Port}" });
}
internal bool CanAcceptConnection()
{
return _config.MaxConnections <= 0 || GetActiveConnectionCount() < _config.MaxConnections;
}
internal void IncrementDroppedConnection() => _stats.IncrementDroppedConnections();
internal bool AddClient(string clientId, GrpcClientConnection connection)
{
if (_clients.TryAdd(clientId, connection))
{
_stats.IncrementTotalConnections();
return true;
}
_stats.IncrementDroppedConnections();
return false;
}
internal bool RemoveClient(string clientId, out GrpcClientConnection? client)
{
var removed = _clients.TryRemove(clientId, out client);
_lastPingTimes.TryRemove(clientId, out _);
return removed;
}
internal void RaiseOnConnected(ConnectionEventArgs args) =>
HandlingHelpers.SafeInvokeEventHandler(OnConnected, this, args, nameof(OnConnected));
internal void RaiseOnDataReceived(DataReceivedEventArgs args)
{
_stats.IncrementMessagesReceived();
HandlingHelpers.SafeInvokeEventHandler(OnDataReceived, this, args, nameof(OnDataReceived));
}
internal void RaiseOnDisconnected(ConnectionEventArgs args) =>
HandlingHelpers.SafeInvokeEventHandler(OnDisconnected, this, args, nameof(OnDisconnected));
internal void RaiseOnGeneralError(ErrorEventArgs args) =>
HandlingHelpers.SafeInvokeEventHandler(OnGeneralError, this, args, nameof(OnGeneralError));
internal void TrackBytesReceived(long bytes) => _stats.AddBytesReceived(bytes);
internal void TrackBytesSent(long bytes) => _stats.AddBytesSent(bytes);
public async Task<bool> SendToClientAsync(string clientId, byte[] data)
{
if (data == null || data.Length == 0)
{
return false;
}
if (!_clients.TryGetValue(clientId, out var client) || client.ResponseStream == null)
{
return false;
}
try
{
await client.WriteLock.WaitAsync().ConfigureAwait(false);
try
{
var message = new ConnectorMessage
{
Type = MessageType.Data,
Data = Google.Protobuf.ByteString.CopyFrom(data)
};
await client.ResponseStream.WriteAsync(message).ConfigureAwait(false);
}
finally
{
client.WriteLock.Release();
}
var sentAt = DateTime.UtcNow;
client.LastDataSent = sentAt;
client.LastActive = sentAt;
client.BytesSent += data.Length;
client.MessagesSent++;
_stats.IncrementMessagesSent();
_stats.AddBytesSent(data.Length);
return true;
}
catch (Exception exception)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
ClientId = clientId,
Nickname = client.Nickname,
Exception = exception,
Message = "Error sending data to gRPC 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)
{
if (data == null || data.Length == 0)
{
return false;
}
bool any = false;
foreach (var client in _clients)
{
if (await SendToClientAsync(client.Key, data).ConfigureAwait(false))
{
any = true;
}
}
return any;
}
public async Task<bool> BroadcastAsync(string message)
=> await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
public async Task<bool> BroadcastExceptAsync(byte[] data, string excludeClientId)
{
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;
}
}
return any;
}
public async Task<bool> BroadcastExceptAsync(string message, string excludeClientId)
=> await BroadcastExceptAsync(Encoding.UTF8.GetBytes(message), excludeClientId).ConfigureAwait(false);
public ConcurrentDictionary<string, GrpcClientConnection> GetClients() => _clients;
public GrpcClientConnection? GetClient(string clientId)
{
_clients.TryGetValue(clientId, out var client);
return client;
}
public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.ServerShutdown)
{
if (!RemoveClient(clientId, out var client))
{
return;
}
try
{
if (client?.ResponseStream != null)
{
await client.WriteLock.WaitAsync().ConfigureAwait(false);
try
{
var msg = new ConnectorMessage { Type = MessageType.Disconnect };
await client.ResponseStream.WriteAsync(msg).ConfigureAwait(false);
}
catch
{
}
finally
{
client.WriteLock.Release();
}
}
client?.CancellationSource?.Cancel();
}
catch
{
}
TrackDisconnect(reason);
HandlingHelpers.SafeInvokeEventHandler(
OnDisconnected,
this,
new ConnectionEventArgs
{
ClientId = clientId,
Nickname = client?.Nickname,
RemoteEndPoint = client?.RemoteEndPoint,
Reason = reason
},
nameof(OnDisconnected));
}
private async Task PingLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false);
foreach (var kvp in _clients)
{
var clientId = kvp.Key;
var client = kvp.Value;
if (client.ResponseStream == null || !client.IsConnected)
{
continue;
}
try
{
await client.WriteLock.WaitAsync(token).ConfigureAwait(false);
try
{
var pingMsg = new ConnectorMessage { Type = MessageType.Ping };
await client.ResponseStream.WriteAsync(pingMsg).ConfigureAwait(false);
}
finally
{
client.WriteLock.Release();
}
client.LastPingSent = DateTime.UtcNow;
_lastPingTimes[clientId] = DateTime.UtcNow;
}
catch (Exception ex)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"Error sending ping to {client.Nickname}: {ex.Message}" });
}
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = ex,
Message = "Ping loop error"
},
nameof(OnGeneralError));
}
}
}
private async Task PongMonitorLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(1), token).ConfigureAwait(false);
var now = DateTime.UtcNow;
var timeout = _config.HeartbeatIntervalSeconds * 2;
foreach (var kvp in _lastPingTimes)
{
var clientId = kvp.Key;
var lastPing = kvp.Value;
if (!_clients.TryGetValue(clientId, out var client))
{
_lastPingTimes.TryRemove(clientId, out _);
continue;
}
var elapsed = (now - client.LastPongReceived).TotalSeconds;
if (client.LastPongReceived == default)
{
elapsed = (now - lastPing).TotalSeconds;
}
if (elapsed > timeout)
{
OnPongMissed?.Invoke(this, new PingEventArgs
{
Id = client.Id,
Nickname = client.Nickname,
ReceivedTime = now,
RemoteEndPoint = client.RemoteEndPoint
});
if (_config.DisconectOnMissedPong)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"gRPC client '{client.Nickname}' no PONG for {elapsed:F1}s, disconnecting." });
_ = DisconnectClientAsync(clientId, DisconnectReason.NoPongReceived);
}
}
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs
{
Exception = ex,
Message = "Pong monitor loop error"
},
nameof(OnGeneralError));
}
}
}
internal void HandlePongReceived(string clientId)
{
if (_clients.TryGetValue(clientId, out var client))
{
client.LastPongReceived = DateTime.UtcNow;
client.LastActive = DateTime.UtcNow;
OnClientPingResponse?.Invoke(this, new PingEventArgs
{
Id = clientId,
Nickname = client.Nickname,
ReceivedTime = DateTime.UtcNow,
RemoteEndPoint = client.RemoteEndPoint
});
}
}
private string BuildHealthJson()
{
var E = HealthApiServer.JsonEscape;
var stats = GetStats();
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"grpc-server\"," +
$"\"listenAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"isStarted\":{(IsStarted ? "true" : "false")}," +
$"\"activeConnections\":{stats.ActiveConnections}," +
$"\"maxConnections\":{_config.MaxConnections}," +
$"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1}," +
$"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))}" +
"}";
}
private string BuildStatusJson()
{
var E = HealthApiServer.JsonEscape;
var stats = GetStats();
var sb = new StringBuilder();
sb.Append("{");
sb.Append("\"status\":\"ok\",");
sb.Append("\"type\":\"grpc-server\",");
sb.Append($"\"listenAddress\":{E(_config.Host + ":" + _config.Port)},");
sb.Append($"\"isStarted\":{(IsStarted ? "true" : "false")},");
sb.Append($"\"activeConnections\":{stats.ActiveConnections},");
sb.Append($"\"maxConnections\":{_config.MaxConnections},");
sb.Append($"\"totalConnections\":{stats.TotalConnections},");
sb.Append($"\"droppedConnections\":{stats.DroppedConnections},");
sb.Append($"\"bytesSent\":{stats.BytesSent},");
sb.Append($"\"bytesReceived\":{stats.BytesReceived},");
sb.Append($"\"messagesSent\":{stats.MessagesSent},");
sb.Append($"\"messagesReceived\":{stats.MessagesReceived},");
sb.Append($"\"messagesPerSecond\":{stats.MessagesPerSecond:F2},");
sb.Append($"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1},");
sb.Append($"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))},");
sb.Append("\"clients\":[");
var clientList = _clients.Values.ToArray();
for (int i = 0; i < clientList.Length; i++)
{
var c = clientList[i];
if (i > 0)
{
sb.Append(",");
}
sb.Append("{");
sb.Append($"\"id\":{E(c.Id)},");
sb.Append($"\"nickname\":{E(c.Nickname)},");
sb.Append($"\"remoteEndPoint\":{E(c.RemoteEndPoint?.ToString())},");
sb.Append($"\"connectedAtUtc\":{E(c.ConnectedAt.ToString("O"))},");
sb.Append($"\"connectedTimeSeconds\":{c.ConnectedTime().TotalSeconds:F1},");
sb.Append($"\"idleTimeSeconds\":{c.IdleTime().TotalSeconds:F1},");
sb.Append($"\"bytesSent\":{c.BytesSent},");
sb.Append($"\"bytesReceived\":{c.BytesReceived},");
sb.Append($"\"messagesSent\":{c.MessagesSent},");
sb.Append($"\"messagesReceived\":{c.MessagesReceived}");
sb.Append("}");
}
sb.Append("]");
sb.Append("}");
return sb.ToString();
}
public void Stop()
{
_serverCts?.Cancel();
foreach (var client in _clients.Keys.ToList())
{
DisconnectClientAsync(client, DisconnectReason.ServerShutdown).GetAwaiter().GetResult();
}
_clients.Clear();
HealthApi.Stop();
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();
HealthApi.Stop();
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
{
}
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
Stop();
_serverCts?.Dispose();
_stats.Dispose();
OnConnected = null;
OnDisconnected = null;
OnDataReceived = null;
OnGeneralError = null;
OnClientPingResponse = null;
OnPongMissed = null;
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
await StopAsync().ConfigureAwait(false);
_serverCts?.Dispose();
_stats.Dispose();
OnConnected = null;
OnDisconnected = null;
OnDataReceived = null;
OnGeneralError = null;
OnClientPingResponse = null;
OnPongMissed = null;
}
}
}
@@ -0,0 +1,23 @@
syntax = "proto3";
option csharp_namespace = "EonaCat.Connections.gRPC.Proto";
package connector;
service ConnectorService {
rpc Connect (stream ConnectorMessage) returns (stream ConnectorMessage);
}
message ConnectorMessage {
MessageType type = 1;
bytes data = 2;
string text = 3;
}
enum MessageType {
DATA = 0;
NICKNAME = 1;
PING = 2;
PONG = 3;
DISCONNECT = 4;
}
+197 -1
View File
@@ -1,7 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 18
VisualStudioVersion = 18.0.11205.157 d18.0
VisualStudioVersion = 18.0.11205.157
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections", "EonaCat.Connections\EonaCat.Connections.csproj", "{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}"
EndProject
@@ -9,24 +9,220 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Client"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Server", "EonaCat.Connections.Server\EonaCat.Connections.Server.csproj", "{B0756C21-1D41-041C-D3D7-76A9A01E0009}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Quic", "EonaCat.Connections.Quic\EonaCat.Connections.Quic.csproj", "{78997F5F-4278-4817-9F8F-C95AB807A812}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Quic.Client", "EonaCat.Connections.Quic.Client\EonaCat.Connections.Quic.Client.csproj", "{35256C8B-48E2-42DC-977F-E2749D2B0284}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Quic.Server", "EonaCat.Connections.Quic.Server\EonaCat.Connections.Quic.Server.csproj", "{2482D3A6-6312-4892-BD57-927F49D4ACD7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.gRPC", "EonaCat.Connections.gRPC\EonaCat.Connections.gRPC.csproj", "{1DF97457-1582-4218-BC07-706FB23021D0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.gRPC.Server", "EonaCat.Connections.gRPC.Server\EonaCat.Connections.gRPC.Server.csproj", "{EB379332-F5E6-48BD-8114-A59014A1E27C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.gRPC.Client", "EonaCat.Connections.gRPC.Client\EonaCat.Connections.gRPC.Client.csproj", "{D0C18902-A38A-4686-A4D2-2A79143C97E4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.REST", "EonaCat.Connections.REST\EonaCat.Connections.REST.csproj", "{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.REST.Server", "EonaCat.Connections.REST.Server\EonaCat.Connections.REST.Server.csproj", "{EB638D1B-A2C3-4184-A276-5C903BEABE9E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.REST.Client", "EonaCat.Connections.REST.Client\EonaCat.Connections.REST.Client.csproj", "{17E8D91B-131F-447C-9FF5-BC87094CFB2F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.OpcUa", "EonaCat.Connections.OpcUa\EonaCat.Connections.OpcUa.csproj", "{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.OpcUa.Client", "EonaCat.Connections.OpcUa.Client\EonaCat.Connections.OpcUa.Client.csproj", "{55E9200D-DF76-476B-ACB0-99727862F9F8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.OpcUa.Server", "EonaCat.Connections.OpcUa.Server\EonaCat.Connections.OpcUa.Server.csproj", "{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x64.ActiveCfg = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x64.Build.0 = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x86.ActiveCfg = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x86.Build.0 = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|Any CPU.Build.0 = Release|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x64.ActiveCfg = Release|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x64.Build.0 = Release|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x86.ActiveCfg = Release|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x86.Build.0 = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|Any CPU.Build.0 = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x64.ActiveCfg = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x64.Build.0 = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x86.ActiveCfg = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x86.Build.0 = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|Any CPU.ActiveCfg = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|Any CPU.Build.0 = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x64.ActiveCfg = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x64.Build.0 = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x86.ActiveCfg = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x86.Build.0 = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x64.ActiveCfg = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x64.Build.0 = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x86.ActiveCfg = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x86.Build.0 = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|Any CPU.Build.0 = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x64.ActiveCfg = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x64.Build.0 = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x86.ActiveCfg = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x86.Build.0 = Release|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|Any CPU.Build.0 = Debug|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x64.ActiveCfg = Debug|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x64.Build.0 = Debug|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x86.ActiveCfg = Debug|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x86.Build.0 = Debug|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Release|Any CPU.ActiveCfg = Release|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Release|Any CPU.Build.0 = Release|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x64.ActiveCfg = Release|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x64.Build.0 = Release|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x86.ActiveCfg = Release|Any CPU
{78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x86.Build.0 = Release|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|Any CPU.Build.0 = Debug|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x64.ActiveCfg = Debug|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x64.Build.0 = Debug|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x86.ActiveCfg = Debug|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x86.Build.0 = Debug|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|Any CPU.ActiveCfg = Release|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|Any CPU.Build.0 = Release|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x64.ActiveCfg = Release|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x64.Build.0 = Release|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x86.ActiveCfg = Release|Any CPU
{35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x86.Build.0 = Release|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x64.ActiveCfg = Debug|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x64.Build.0 = Debug|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x86.ActiveCfg = Debug|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x86.Build.0 = Debug|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|Any CPU.Build.0 = Release|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x64.ActiveCfg = Release|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x64.Build.0 = Release|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x86.ActiveCfg = Release|Any CPU
{2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x86.Build.0 = Release|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x64.ActiveCfg = Debug|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x64.Build.0 = Debug|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x86.ActiveCfg = Debug|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x86.Build.0 = Debug|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Release|Any CPU.Build.0 = Release|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Release|x64.ActiveCfg = Release|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Release|x64.Build.0 = Release|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Release|x86.ActiveCfg = Release|Any CPU
{1DF97457-1582-4218-BC07-706FB23021D0}.Release|x86.Build.0 = Release|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x64.ActiveCfg = Debug|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x64.Build.0 = Debug|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x86.ActiveCfg = Debug|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x86.Build.0 = Debug|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|Any CPU.Build.0 = Release|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x64.ActiveCfg = Release|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x64.Build.0 = Release|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x86.ActiveCfg = Release|Any CPU
{EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x86.Build.0 = Release|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x64.ActiveCfg = Debug|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x64.Build.0 = Debug|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x86.ActiveCfg = Debug|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x86.Build.0 = Debug|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|Any CPU.Build.0 = Release|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x64.ActiveCfg = Release|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x64.Build.0 = Release|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x86.ActiveCfg = Release|Any CPU
{D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x86.Build.0 = Release|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x64.ActiveCfg = Debug|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x64.Build.0 = Debug|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x86.ActiveCfg = Debug|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x86.Build.0 = Debug|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|Any CPU.Build.0 = Release|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x64.ActiveCfg = Release|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x64.Build.0 = Release|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x86.ActiveCfg = Release|Any CPU
{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x86.Build.0 = Release|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x64.ActiveCfg = Debug|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x64.Build.0 = Debug|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x86.ActiveCfg = Debug|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x86.Build.0 = Debug|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|Any CPU.Build.0 = Release|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x64.ActiveCfg = Release|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x64.Build.0 = Release|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x86.ActiveCfg = Release|Any CPU
{EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x86.Build.0 = Release|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x64.ActiveCfg = Debug|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x64.Build.0 = Debug|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x86.ActiveCfg = Debug|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x86.Build.0 = Debug|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|Any CPU.Build.0 = Release|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x64.ActiveCfg = Release|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x64.Build.0 = Release|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x86.ActiveCfg = Release|Any CPU
{17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x86.Build.0 = Release|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x64.ActiveCfg = Debug|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x64.Build.0 = Debug|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x86.ActiveCfg = Debug|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x86.Build.0 = Debug|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|Any CPU.Build.0 = Release|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x64.ActiveCfg = Release|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x64.Build.0 = Release|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x86.ActiveCfg = Release|Any CPU
{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x86.Build.0 = Release|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x64.ActiveCfg = Debug|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x64.Build.0 = Debug|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x86.ActiveCfg = Debug|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x86.Build.0 = Debug|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|Any CPU.Build.0 = Release|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x64.ActiveCfg = Release|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x64.Build.0 = Release|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x86.ActiveCfg = Release|Any CPU
{55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x86.Build.0 = Release|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x64.ActiveCfg = Debug|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x64.Build.0 = Debug|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x86.ActiveCfg = Debug|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x86.Build.0 = Debug|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|Any CPU.Build.0 = Release|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x64.ActiveCfg = Release|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x64.Build.0 = Release|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x86.ActiveCfg = Release|Any CPU
{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+15 -7
View File
@@ -1,13 +1,21 @@
namespace EonaCat.Connections
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
internal enum BufferSizeMaximum
{
Minimal = 8192,
Medium = 65536,
Large = 262144,
ExtraLarge = 1048576,
Small = 32 * 1024,
Medium = 128 * 1024,
Large = 512 * 1024,
ExtraLarge = 1 * 1024 * 1024,
Huge = 8 * 1024 * 1024
}
internal enum MessageSizeMaximum
{
Small = 16 * 1024 * 1024,
Medium = 32 * 1024 * 1024,
Large = 64 * 1024 * 1024,
ExtraLarge = 128 * 1024 * 1024,
Huge = 256 * 1024 * 1024,
Default = 32 * 1024 * 1024
}
}
+18
View File
@@ -0,0 +1,18 @@
namespace EonaCat.Connections
{
public enum LogType
{
None = 0,
Info = 1,
Warning = 2,
Error = 3,
Debug = 4,
Trace = 5
}
public class LogMessage
{
public LogType Type { get; set; }
public string Message { get; set; }
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,73 @@
using EonaCat.Connections.Models;
using System.Net.Sockets;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections
{
public partial class NetworkClient
{
private static void FireAndForget(Task task, string context)
{
if (task == null)
{
return;
}
if (task.IsCompleted)
{
if (task.IsFaulted)
{
OnLog?.Invoke(null, new LogMessage { Type = LogType.Error, Message = $"Unobserved exception in {context}: {task.Exception?.Flatten().Message}" });
}
return;
}
_ = task.ContinueWith(t =>
{
OnLog?.Invoke(null, new LogMessage { Type = LogType.Error, Message = $"Unobserved exception in {context}: {t.Exception?.Flatten().Message}" });
}, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
private void DebugConnection(string debugText)
{
if (!_config.EnableConnectionDebugLogs)
{
return;
}
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[NetworkClient] {debugText}" });
}
private void RecordError(Exception exception, string message, string clientId = null, string nickname = null, bool isSslError = false)
{
var socketEx = exception as SocketException
?? (exception as IOException)?.InnerException as SocketException;
var entry = new SocketErrorEntry
{
Timestamp = DateTime.UtcNow,
Source = "Client",
ClientId = clientId ?? Nickname ?? "self",
Nickname = nickname ?? Nickname,
SocketErrorCode = socketEx?.SocketErrorCode,
ErrorCode = socketEx != null ? socketEx.SocketErrorCode.ToString() : exception?.GetType().Name,
Message = message,
ExceptionType = exception?.GetType().FullName,
StackTrace = exception?.StackTrace,
Exception = exception,
IsSslError = isSslError
};
StatusPage.AddError(entry);
if (socketEx != null)
{
OnSocketError?.Invoke(this, new ErrorEventArgs
{
ClientId = entry.ClientId,
Nickname = entry.Nickname,
Exception = exception,
Message = $"SocketError {socketEx.SocketErrorCode}: {message}"
});
}
}
}
}
@@ -0,0 +1,225 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections
{
public partial class NetworkClient
{
private async Task StartPingLoopAsync(CancellationToken token)
{
var interval = TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds);
var next = DateTime.UtcNow + interval;
try
{
while (!token.IsCancellationRequested && IsConnected)
{
try
{
if (_stream == null || !_stream.CanWrite)
{
DebugConnection("Ping loop stopping - stream not available for writing");
break;
}
var result = await SendInternalAsync(PingBytes, token).ConfigureAwait(false);
if (result)
{
LastPingSent = DateTime.UtcNow;
if (_config.EnablePingPongLogs)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[PING] Sent at {DateTime.UtcNow:O}" });
}
}
else
{
DebugConnection("Ping loop failed to send ping - will retry on next interval");
}
var delay = next - DateTime.UtcNow;
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, token).ConfigureAwait(false);
}
next += interval;
}
catch (OperationCanceledException)
{
DebugConnection($"Ping loop: Operation canceled for {_config.Host}:{_config.Port}");
break;
}
catch (Exception exception)
{
DebugConnection($"Ping loop: Error sending ping to {_config.Host}:{_config.Port}: {exception.GetType().Name} - {exception.Message}");
RecordError(exception, $"Ping loop error: {exception.GetType().Name} - {exception.Message}");
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[PING] Error sending ping: {exception.GetType().Name} - {exception.Message}" });
break;
}
}
}
catch (Exception ex)
{
DebugConnection($"Ping loop: Unexpected error: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Ping loop unexpected error: {ex.GetType().Name}");
}
finally
{
DebugConnection("Ping loop stopped.");
}
}
private async Task StartPongLoop(CancellationToken token)
{
var interval = TimeSpan.FromSeconds(1);
var next = DateTime.UtcNow + interval;
try
{
while (!token.IsCancellationRequested)
{
try
{
if (!IsConnected)
{
DebugConnection("Pong loop stopping - client disconnected");
break;
}
var elapsed = (DateTime.UtcNow - LastPongReceived).TotalSeconds;
if (_hasReceivedPongSinceConnection &&
elapsed > _config.HeartbeatIntervalSeconds * 5)
{
var msg = $"No PONG received for {elapsed:F1}s (threshold: {_config.HeartbeatIntervalSeconds * 5}s) - connection is stale";
DebugConnection($"Pong monitor: {msg}");
RecordError(null, msg);
var disconnectReason = DisconnectOnMissedPong ? DisconnectReason.NoPongReceived : DisconnectReason.Timeout;
await DisconnectClientAsync(disconnectReason);
break;
}
var delay = next - DateTime.UtcNow;
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, token);
}
next += interval;
}
catch (OperationCanceledException)
{
DebugConnection($"Pong loop: Operation canceled for {_config.Host}:{_config.Port}");
break;
}
catch (Exception ex)
{
DebugConnection($"Pong loop: Error monitoring pong for {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Pong loop error: {ex.GetType().Name} - {ex.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ex);
break;
}
}
}
catch (Exception ex)
{
DebugConnection($"Pong loop: Unexpected error: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Pong loop unexpected error: {ex.GetType().Name}");
}
finally
{
DebugConnection("Pong loop stopped.");
}
}
private byte[] HandleHeartbeat(byte[] data, out bool hasHeartbeat)
{
hasHeartbeat = false;
if (!_config.EnableHeartbeat || data == null || data.Length == 0)
{
return data;
}
string text = null;
try
{
text = Encoding.UTF8.GetString(data);
}
catch
{
}
if (string.IsNullOrEmpty(text))
{
return data;
}
if (text.Contains("[DISCONNECT]", StringComparison.OrdinalIgnoreCase))
{
FireAndForget(DisconnectClientAsync(DisconnectReason.RemoteClosed), "heartbeat DISCONNECT");
hasHeartbeat = true;
}
if (text.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase))
{
string sslError = null;
var startIdx = text.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length;
var endIdx = text.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal);
if (endIdx > startIdx)
{
sslError = text.Substring(startIdx, endIdx - startIdx);
}
RecordError(null, $"Server reported SSL error: {sslError ?? text}", isSslError: true);
HandlingHelpers.SafeInvokeEventHandler(
OnSslError,
this,
new ErrorEventArgs
{
Message = $"Server reported SSL error: {sslError ?? text}"
},
nameof(OnSslError));
FireAndForget(DisconnectClientAsync(DisconnectReason.SSLError), "heartbeat SSL error disconnect");
hasHeartbeat = true;
}
if (text.Contains(Configuration.PING_VALUE))
{
hasHeartbeat = true;
FireAndForget(SendAsync(Configuration.PONG_VALUE), "heartbeat PONG send");
if (_config.EnablePingPongLogs)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "PING received. Sent PONG response." });
}
}
if (text.Contains(Configuration.PONG_VALUE))
{
hasHeartbeat = true;
var now = DateTime.UtcNow;
OnPingResponse?.Invoke(this, new PingEventArgs
{
Id = "server",
Nickname = Nickname,
ReceivedTime = now,
RemoteEndPoint = GetRemoteEndPoint()
});
if (_config.EnablePingPongLogs)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "PONG received." });
}
}
if (hasHeartbeat && !string.IsNullOrEmpty(text))
{
text = text.Replace(Configuration.PING_VALUE, string.Empty).Replace(Configuration.PONG_VALUE, string.Empty).Replace("[DISCONNECT]", string.Empty);
data = Encoding.UTF8.GetBytes(text);
}
return data;
}
}
}
@@ -0,0 +1,679 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Framing;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using System.Buffers;
using System.Net;
using System.Net.Sockets;
using System.Text;
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections
{
public partial class NetworkClient
{
private async Task ReceiveDataAsync(CancellationToken token)
{
DebugConnection($"ReceiveDataAsync started for {_config.Host}:{_config.Port} with framing mode {_config.MessageFraming}");
try
{
switch (_config.MessageFraming)
{
case FramingMode.LengthPrefixed:
await ReceiveLengthPrefixedAsync(token);
break;
case FramingMode.Delimiter:
await ReceiveDelimiterAsync(token);
break;
case FramingMode.None:
await ReceiveNoneAsync(token);
break;
}
}
catch (OperationCanceledException ex)
{
DebugConnection("Receive loop cancelled by cancellation token.");
RecordError(ex, "Receive loop cancellation requested");
}
catch (SocketException socketEx)
{
var errorMsg = $"Socket error in receive loop: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote", SocketError.ConnectionAborted => "Connection aborted", SocketError.TimedOut => "Receive timeout", _ => "Unknown socket error" }}";
RecordError(socketEx, errorMsg);
DebugConnection($"Receive loop socket error: {socketEx.SocketErrorCode} - {socketEx.Message}");
var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, socketEx);
}
catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx)
{
var errorMsg = $"Socket IO error in receive loop: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}";
RecordError(ioEx, errorMsg);
DebugConnection($"Receive loop socket IO error: {innerSocketEx.SocketErrorCode} - {ioEx.Message}");
var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset
|| innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, ioEx);
}
catch (IOException ioEx)
{
DebugConnection($"IO error in receive loop: {ioEx.GetType().Name} - {ioEx.Message}");
RecordError(ioEx, $"IO error in receive loop: {ioEx.GetType().Name}");
await DisconnectClientAsync(DisconnectReason.Error, ioEx);
}
catch (Exception ex)
{
DebugConnection($"Unexpected error in receive loop: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Receive loop error: {ex.GetType().Name} - {ex.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ex);
}
finally
{
DebugConnection("Receive loop exited.");
}
}
private async Task ReceiveLengthPrefixedAsync(CancellationToken token)
{
int prefixSize = _config.LengthPrefixedLength;
if (prefixSize < 1 || prefixSize > 8)
{
throw new InvalidOperationException("LengthPrefixedLength must be between 1 and 8.");
}
byte[] lengthBuffer = ArrayPool<byte>.Shared.Rent(prefixSize);
try
{
while (!token.IsCancellationRequested && IsConnected)
{
var stream = _stream;
if (stream == null || !stream.CanRead)
{
break;
}
CancellationToken readToken = token;
using var cts = _config.ReadTimeoutSeconds > 0
? CancellationTokenSource.CreateLinkedTokenSource(token)
: null;
if (cts != null)
{
cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds));
readToken = cts.Token;
}
await ReadExactAsync(stream, lengthBuffer, 0, prefixSize, readToken).ConfigureAwait(false);
long length = ParseLengthPrefix(lengthBuffer, prefixSize, _config.UseBigEndian);
if (length <= 0 || length > _config.MAX_MESSAGE_SIZE)
{
throw new InvalidOperationException($"Invalid message length {length}");
}
byte[] buffer = ArrayPool<byte>.Shared.Rent((int)length);
try
{
await ReadExactAsync(stream, buffer, 0, (int)length, readToken).ConfigureAwait(false);
if (_config.UseAesEncryption && _aesEncryption != null)
{
var decrypted = await AesKeyExchange.DecryptDataAsync(buffer.AsSpan(0, (int)length).ToArray(), (int)length, _aesEncryption).ConfigureAwait(false);
await ProcessReceivedDataAsync(decrypted).ConfigureAwait(false);
}
else
{
await ProcessReceivedDataAsync(buffer.AsMemory(0, (int)length)).ConfigureAwait(false);
}
MarkDataReceived();
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
catch (OperationCanceledException ex)
{
DebugConnection($"Length-prefixed read timeout: {ex.Message}");
RecordError(ex, "Read timeout during length-prefixed receive - stream may have hung");
await DisconnectClientAsync(DisconnectReason.Timeout, ex);
}
catch (SocketException socketEx)
{
DebugConnection($"Socket error in length-prefixed receive: {socketEx.SocketErrorCode} - {socketEx.Message}");
RecordError(socketEx, $"Socket error in length-prefixed receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}");
var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, socketEx);
}
catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx)
{
DebugConnection($"Socket IO error in length-prefixed receive: {innerSocketEx.SocketErrorCode} - {ex.Message}");
RecordError(ex, $"Socket IO error in length-prefixed receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}");
var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset
|| innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, ex);
}
catch (IOException ex)
{
DebugConnection($"Connection closed during length-prefixed receive: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, "Connection closed during length-prefixed receive");
await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex);
}
catch (Exception ex)
{
DebugConnection($"Unexpected error in length-prefixed receive: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Unexpected error in length-prefixed receive: {ex.GetType().Name} - {ex.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ex);
}
finally
{
ArrayPool<byte>.Shared.Return(lengthBuffer);
}
}
private long ParseLengthPrefix(byte[] buffer, int length, bool useBigEndian)
{
var value = MessageFrameDecoder.ParseLengthPrefix(buffer, length, useBigEndian);
if (value > _config.MAX_MESSAGE_SIZE)
{
throw new InvalidOperationException(
$"Parsed message length {value} exceeds maximum allowed {_config.MAX_MESSAGE_SIZE}. Possible malformed or malicious message.");
}
return value;
}
private async Task ReceiveNoneAsync(CancellationToken token)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
try
{
while (!token.IsCancellationRequested && IsConnected)
{
var stream = _stream;
if (stream == null || !stream.CanRead)
{
break;
}
CancellationToken readToken = token;
using var cts = _config.ReadTimeoutSeconds > 0
? CancellationTokenSource.CreateLinkedTokenSource(token)
: null;
if (cts != null)
{
cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds));
readToken = cts.Token;
}
int read = await stream.ReadAsync(buffer, 0, buffer.Length, readToken);
if (read == 0)
{
DebugConnection("Remote closed connection.");
await DisconnectClientAsync(DisconnectReason.RemoteClosed);
return;
}
ReadOnlyMemory<byte> payload = buffer.AsMemory(0, read);
if (_config.UseAesEncryption && _aesEncryption != null)
{
try
{
var decrypted = await AesKeyExchange.DecryptDataAsync(payload.ToArray(), read, _aesEncryption);
await ProcessReceivedDataAsync(decrypted);
}
catch (Exception ex)
{
DebugConnection($"Decrypt error: {ex.Message}");
HandlingHelpers.SafeInvokeEventHandler(
OnEncryptionError,
this,
new ErrorEventArgs
{
Exception = ex,
Message = "Error decrypting data"
},
nameof(OnEncryptionError));
}
}
else
{
await ProcessReceivedDataAsync(payload);
}
MarkDataReceived();
}
}
catch (OperationCanceledException ex)
{
DebugConnection($"Read timeout during raw receive: {ex.Message}");
RecordError(ex, "Read timeout in raw receive - stream may be unresponsive");
await DisconnectClientAsync(DisconnectReason.Timeout, ex);
}
catch (SocketException socketEx)
{
DebugConnection($"Socket error in raw receive: {socketEx.SocketErrorCode} - {socketEx.Message}");
var errorMsg = $"Socket error in raw receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}";
RecordError(socketEx, errorMsg);
var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, socketEx);
}
catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx)
{
DebugConnection($"Socket IO error in raw receive: {innerSocketEx.SocketErrorCode} - {ex.Message}");
var errorMsg = $"Socket IO error in raw receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}";
RecordError(ex, errorMsg);
var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset
|| innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, ex);
}
catch (IOException ex)
{
DebugConnection($"Connection closed during raw receive: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, "Connection closed during raw receive");
await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex);
}
catch (Exception ex)
{
DebugConnection($"Unexpected error in raw receive: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Error in raw receive: {ex.GetType().Name} - {ex.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ex);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private async Task ReceiveDelimiterAsync(CancellationToken token)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
var memory = new MemoryStream();
try
{
while (!token.IsCancellationRequested && IsConnected)
{
var stream = _stream;
if (stream == null || !stream.CanRead)
{
break;
}
CancellationToken readToken = token;
using var cts = _config.ReadTimeoutSeconds > 0
? CancellationTokenSource.CreateLinkedTokenSource(token)
: null;
if (cts != null)
{
cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds));
readToken = cts.Token;
}
int read = await stream.ReadAsync(buffer, 0, buffer.Length, readToken);
if (read == 0)
{
DebugConnection("Remote closed connection.");
await DisconnectClientAsync(DisconnectReason.RemoteClosed);
return;
}
memory.Write(buffer, 0, read);
while (TryExtractMessage(memory, _config.Delimiter, _config.MAX_MESSAGE_SIZE, out var message))
{
if (_config.UseAesEncryption && _aesEncryption != null)
{
message = await AesKeyExchange.DecryptDataAsync(message, message.Length, _aesEncryption);
}
await ProcessReceivedDataAsync(message);
MarkDataReceived();
}
}
}
catch (ProtocolViolationException ex)
{
DebugConnection($"Protocol violation during delimiter receive: {ex.Message}");
RecordError(ex, $"Protocol violation during delimiter receive: {ex.Message}");
await DisconnectClientAsync(DisconnectReason.ProtocolError, ex);
}
catch (OperationCanceledException ex)
{
DebugConnection($"Read timeout during delimiter receive: {ex.Message}");
RecordError(ex, "Read timeout in delimiter receive - stream may be unresponsive");
await DisconnectClientAsync(DisconnectReason.Timeout, ex);
}
catch (SocketException socketEx)
{
DebugConnection($"Socket error in delimiter receive: {socketEx.SocketErrorCode} - {socketEx.Message}");
var errorMsg = $"Socket error in delimiter receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}";
RecordError(socketEx, errorMsg);
var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, socketEx);
}
catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx)
{
DebugConnection($"Socket IO error in delimiter receive: {innerSocketEx.SocketErrorCode} - {ex.Message}");
var errorMsg = $"Socket IO error in delimiter receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}";
RecordError(ex, errorMsg);
var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset
|| innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted
? DisconnectReason.RemoteClosed
: DisconnectReason.Error;
await DisconnectClientAsync(reason, ex);
}
catch (IOException ex)
{
DebugConnection($"Connection closed during delimiter receive: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, "Connection closed during delimiter receive");
await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex);
}
catch (Exception ex)
{
DebugConnection($"Unexpected error in delimiter receive: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Error in delimiter receive: {ex.GetType().Name} - {ex.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ex);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
memory.Dispose();
}
}
private static bool TryExtractMessage(MemoryStream stream, byte[] delimiter, double maxMessageBytes, out byte[] message)
{
var hasMessage = MessageFrameDecoder.TryReadDelimited(stream, delimiter, maxMessageBytes, out var decodedMessage);
message = decodedMessage ?? Array.Empty<byte>();
return hasMessage;
}
private async Task<int> ReadExactAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken token)
{
int totalRead = 0;
while (totalRead < count && !token.IsCancellationRequested)
{
int bytesRead = await stream.ReadAsync(buffer, offset + totalRead, count - totalRead, token).ConfigureAwait(false);
if (bytesRead == 0)
{
DebugConnection($"Unexpected end of stream: expected {count} bytes, got {totalRead}");
throw new EndOfStreamException($"Unexpected end of stream: expected {count} bytes, got {totalRead}");
}
totalRead += bytesRead;
}
return totalRead;
}
private async Task ProcessReceivedDataAsync(ReadOnlyMemory<byte> data)
{
if (data.IsEmpty)
{
return;
}
MarkDataReceived();
Interlocked.Add(ref _bytesReceived, data.Length);
Interlocked.Increment(ref _messagesReceived);
bool needsText = _config.EnableHeartbeat || OnDataReceived != null;
string stringData = null;
bool isText = false;
if (needsText)
{
try
{
#if NET8_0_OR_GREATER
var span = data.Span;
int charCount = Encoding.UTF8.GetCharCount(span);
if (_charBuffer.Length < charCount)
{
_charBuffer = new char[charCount];
}
int written = Encoding.UTF8.GetChars(span, _charBuffer);
#else
byte[] bytes = data.ToArray();
int charCount = _utf8Decoder.GetCharCount(bytes, 0, bytes.Length);
if (_charBuffer.Length < charCount)
{
_charBuffer = new char[charCount];
}
int written = _utf8Decoder.GetChars(bytes, 0, bytes.Length, _charBuffer, 0);
#endif
if (written > 0)
{
stringData = new string(_charBuffer, 0, written);
isText = true;
}
}
catch
{
isText = false;
}
}
if (_config.EnableHeartbeat && isText)
{
ProcessPingPong(ref stringData);
if (string.IsNullOrEmpty(stringData))
{
return;
}
}
if (isText && !string.IsNullOrEmpty(stringData) && stringData.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase))
{
string sslError = null;
var startIdx = stringData.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length;
var endIdx = stringData.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal);
if (endIdx > startIdx)
{
sslError = stringData.Substring(startIdx, endIdx - startIdx);
}
RecordError(null, $"Server reported SSL error: {sslError ?? stringData}", isSslError: true);
HandlingHelpers.SafeInvokeEventHandler(
OnSslError,
this,
new ErrorEventArgs
{
Message = $"Server reported SSL error: {sslError ?? stringData}"
},
nameof(OnSslError));
await DisconnectClientAsync(DisconnectReason.SSLError).ConfigureAwait(false);
return;
}
if (DEBUG_DATA_RECEIVED)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[DEBUG DATA] Received {data.Length} bytes" });
}
try
{
byte[] sanitizedData = SanitizeReceivedData(data.ToArray());
HandlingHelpers.SafeInvokeEventHandler(
OnDataReceived,
this,
new DataReceivedEventArgs
{
ClientId = "server",
Data = sanitizedData,
IsBinary = !isText,
Timestamp = DateTime.UtcNow,
RemoteEndPoint = GetRemoteEndPoint(),
Nickname = Nickname,
},
nameof(OnDataReceived));
}
catch (Exception ex)
{
DebugConnection($"OnDataReceived handler threw: {ex.GetType().Name} - {ex.Message}");
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"OnDataReceived handler threw: {ex.GetType().Name} - {ex.Message}" });
}
}
private void ProcessPingPong(ref string message)
{
if (!_config.EnableHeartbeat || string.IsNullOrEmpty(message))
{
return;
}
if (message.Contains(Configuration.PING_VALUE))
{
LastPingSent = DateTime.UtcNow;
if (_config.EnablePingPongLogs)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Received PING from server. Sending PONG response." });
}
OnPingResponse?.Invoke(this, new PingEventArgs
{
Id = "server",
Nickname = Nickname,
ReceivedTime = DateTime.UtcNow,
RemoteEndPoint = GetRemoteEndPoint()
});
FireAndForget(SendAsync(Configuration.PONG_VALUE), "PONG send");
message = message.Replace(Configuration.PING_VALUE, string.Empty);
}
if (message.Contains(Configuration.PONG_VALUE))
{
LastPongReceived = DateTime.UtcNow;
_hasReceivedPongSinceConnection = true;
if (_config.EnablePingPongLogs)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Received PONG from server for PING" });
}
OnPongResponse?.Invoke(this, new PingEventArgs
{
Id = "server",
Nickname = Nickname,
ReceivedTime = DateTime.UtcNow,
RemoteEndPoint = GetRemoteEndPoint()
});
message = message.Replace(Configuration.PONG_VALUE, string.Empty);
}
}
private async Task ReceiveUdpDataAsync()
{
DebugConnection($"UDP receive loop started for {_config.Host}:{_config.Port}");
while (_connectionCts != null && !_connectionCts.Token.IsCancellationRequested && IsConnected)
{
try
{
var result = await _udpClient.ReceiveAsync().ConfigureAwait(false);
var buffer = result.Buffer;
if (_config.EnableHeartbeat)
{
try
{
buffer = HandleHeartbeat(buffer, out bool foundHeartbeat);
if (foundHeartbeat)
{
LastPongReceived = DateTime.UtcNow;
_hasReceivedPongSinceConnection = true;
if (_config.EnablePingPongLogs)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Received PONG from server for PING (UDP)" });
}
}
if (buffer == null || buffer.Length == 0)
{
continue;
}
}
catch (Exception exception)
{
DebugConnection($"Heartbeat handling error in UDP: {exception.GetType().Name} - {exception.Message}");
RecordError(exception, $"Heartbeat handling failed (UDP): {exception.GetType().Name} - {exception.Message}");
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs { Exception = exception, Message = "Heartbeat handling failed (UDP)" },
nameof(OnGeneralError));
}
}
MarkDataReceived();
await ProcessReceivedDataAsync(buffer).ConfigureAwait(false);
}
catch (SocketException socketEx)
{
var errorMsg = $"Socket error in UDP receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.HostUnreachable => "Host unreachable", _ => "Unknown socket error" }}";
DebugConnection($"UDP receive socket error: {socketEx.SocketErrorCode} - {socketEx.Message}");
RecordError(socketEx, errorMsg);
HandlingHelpers.SafeInvokeEventHandler(
OnGeneralError,
this,
new ErrorEventArgs { Exception = socketEx, Message = errorMsg },
nameof(OnGeneralError));
ConnectionTime = DateTime.MinValue;
break;
}
catch (ObjectDisposedException ex)
{
DebugConnection("UDP receive loop: UDP client disposed, stopping receive loop.");
RecordError(ex, "UDP client disposed - connection closing");
break;
}
catch (OperationCanceledException)
{
DebugConnection("UDP receive loop: Operation canceled.");
break;
}
catch (Exception exception)
{
DebugConnection($"UDP receive error: {exception.GetType().Name} - {exception.Message}");
RecordError(exception, $"Error receiving UDP data: {exception.GetType().Name} - {exception.Message}");
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = exception, Message = $"UDP receive error: {exception.GetType().Name}" });
ConnectionTime = DateTime.MinValue;
break;
}
}
DebugConnection("UDP receive loop stopped.");
}
}
}
@@ -0,0 +1,163 @@
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections
{
public partial class NetworkClient
{
private async Task AutoReconnectAsync(CancellationToken token)
{
IsAutoConnectStarted = true;
int consecutiveFailures = 0;
const int MAX_CONSECUTIVE_FAILURES = 10;
const int MAX_BACKOFF_SECONDS = 300;
try
{
while (!token.IsCancellationRequested)
{
if (!_config.EnableAutoReconnect ||
_reason == DisconnectReason.LocalClosed ||
!_wasConnected)
{
DebugConnection("Auto-reconnect disabled or not previously connected; stopping auto-reconnect task.");
break;
}
if (_reason == DisconnectReason.ClientRequested)
{
DebugConnection("Client explicitly requested disconnection; stopping auto-reconnect task.");
_autoReconnectSource?.Cancel();
break;
}
if (IsConnected)
{
consecutiveFailures = 0;
await Task.Delay(1_000, token).ConfigureAwait(false);
continue;
}
bool reconnected = await TryReconnectWithRetriesAsync(token).ConfigureAwait(false);
if (reconnected)
{
consecutiveFailures = 0;
}
else
{
consecutiveFailures++;
if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES)
{
var criticalMsg = $"Too many consecutive reconnection failures ({consecutiveFailures}); stopping auto-reconnect task to prevent resource exhaustion.";
DebugConnection(criticalMsg);
RecordError(null, criticalMsg);
break;
}
int baseBackoffSeconds = Math.Min(
(int)Math.Pow(2, Math.Min(consecutiveFailures - 1, 8)),
MAX_BACKOFF_SECONDS
);
var jitter = new Random().Next((int)(baseBackoffSeconds * -0.25), (int)(baseBackoffSeconds * 0.25));
int finalBackoffSeconds = Math.Max(1, baseBackoffSeconds + jitter);
DebugConnection($"Reconnection failed (attempt {consecutiveFailures}); waiting {finalBackoffSeconds}s (base: {baseBackoffSeconds}s) before next attempt...");
try
{
await Task.Delay(TimeSpan.FromSeconds(finalBackoffSeconds), token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
}
}
catch (OperationCanceledException)
{
DebugConnection("Auto-reconnect task canceled.");
}
catch (Exception ex)
{
DebugConnection($"Auto-reconnect task encountered unexpected error: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Auto-reconnect task failed: {ex.GetType().Name} - {ex.Message}");
}
finally
{
IsAutoConnectStarted = false;
DebugConnection("Auto-reconnect task stopped.");
}
}
private async Task<bool> TryReconnectWithRetriesAsync(CancellationToken token)
{
int attempt = 0;
var maxAttempts = _config.MaxReconnectAttempts;
while (!token.IsCancellationRequested && (maxAttempts == 0 || attempt < maxAttempts))
{
if (IsConnected)
{
return true;
}
attempt++;
try
{
DebugConnection($"Attempting to reconnect... Attempt {attempt}/{(maxAttempts == 0 ? "unlimited" : maxAttempts.ToString())}");
var connected = await ConnectAsync().ConfigureAwait(false);
if (connected && IsConnected)
{
_reason = DisconnectReason.Unknown;
var successMsg = $"Reconnected successfully after {attempt} attempt(s)";
DebugConnection(successMsg);
return true;
}
}
catch (OperationCanceledException)
{
DebugConnection($"Reconnection attempt {attempt} canceled.");
throw;
}
catch (Exception ex)
{
var errorMsg = $"Reconnection attempt {attempt} failed: {ex.GetType().Name} - {ex.Message}";
DebugConnection(errorMsg);
RecordError(ex, errorMsg);
OnGeneralError?.Invoke(
this,
new ErrorEventArgs
{
Exception = ex,
Message = errorMsg
});
}
if (maxAttempts > 0 && attempt >= maxAttempts)
{
DebugConnection($"Maximum reconnection attempts ({maxAttempts}) reached.");
break;
}
Int32 retryDelayMs = Math.Min(500 * attempt, 2000);
try
{
await Task.Delay(retryDelayMs, token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
return false;
}
}
}
@@ -0,0 +1,418 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Framing;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Messaging;
using EonaCat.Connections.Models;
using System.Net.Sockets;
using System.Text;
using ProtocolType = EonaCat.Connections.Models.ProtocolType;
namespace EonaCat.Connections
{
public partial class NetworkClient
{
public async Task<bool> SendAsync(byte[] data)
=> await SendAsync(data, CancellationToken.None).ConfigureAwait(false);
public async Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
if (data == null || data.Length == 0)
{
DebugConnection("SendAsync: Cannot send null or empty data");
return false;
}
if (!IsConnected)
{
DebugConnection("SendAsync: Not connected, cannot send");
return false;
}
if (_clientCts == null || _clientCts.IsCancellationRequested)
{
DebugConnection("SendAsync: Client cancellation token is invalid");
return false;
}
try
{
using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(_clientCts.Token, cancellationToken);
byte[] payload = data;
if (_config.UseAesEncryption && _aesEncryption != null)
{
payload = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesEncryption);
}
byte[] framed = Frame(payload);
return await SendWithRetryAsync(framed, linkedSource.Token).ConfigureAwait(false);
}
catch (Exception ex)
{
DebugConnection($"SendAsync: Unexpected error in send operation: {ex.GetType().Name} - {ex.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ex);
return false;
}
}
private async Task<bool> SendWithRetryAsync(byte[] data, CancellationToken token)
{
int retryCount = 0;
int delayMs = SEND_RETRY_INITIAL_DELAY_MS;
while (retryCount <= SEND_RETRY_MAX_ATTEMPTS)
{
try
{
if (token.IsCancellationRequested)
{
DebugConnection("SendWithRetryAsync: Operation canceled");
return false;
}
bool result = await SendInternalAsync(data, token).ConfigureAwait(false);
if (result)
{
if (retryCount > 0)
{
DebugConnection($"SendWithRetryAsync: Send succeeded on retry attempt {retryCount}");
}
return true;
}
if (token.IsCancellationRequested)
{
return false;
}
retryCount++;
if (retryCount <= SEND_RETRY_MAX_ATTEMPTS)
{
if (!IsConnected)
{
DebugConnection($"SendWithRetryAsync: Not connected, triggering auto-reconnect (attempt {retryCount}/{SEND_RETRY_MAX_ATTEMPTS})");
if (_config.EnableAutoReconnect && _autoReconnectTask != null && !_autoReconnectTask.IsCompleted)
{
await Task.Delay(delayMs, token).ConfigureAwait(false);
}
else if (_config.EnableAutoReconnect)
{
await ConnectAsync().ConfigureAwait(false);
}
}
else
{
DebugConnection($"SendWithRetryAsync: Send failed, retrying after {delayMs}ms (attempt {retryCount}/{SEND_RETRY_MAX_ATTEMPTS})");
await Task.Delay(delayMs, token).ConfigureAwait(false);
}
delayMs = Math.Min(delayMs * 2, SEND_RETRY_MAX_DELAY_MS);
}
}
catch (OperationCanceledException)
{
DebugConnection("SendWithRetryAsync: Operation canceled during retry");
return false;
}
catch (Exception ex)
{
DebugConnection($"SendWithRetryAsync: Exception during send attempt: {ex.GetType().Name} - {ex.Message}");
retryCount++;
if (retryCount <= SEND_RETRY_MAX_ATTEMPTS)
{
DebugConnection($"SendWithRetryAsync: Retrying after exception (attempt {retryCount}/{SEND_RETRY_MAX_ATTEMPTS})");
if (!IsConnected && _config.EnableAutoReconnect)
{
DebugConnection("SendWithRetryAsync: Connection lost, triggering auto-reconnect");
await ConnectAsync().ConfigureAwait(false);
}
try
{
await Task.Delay(delayMs, token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return false;
}
delayMs = Math.Min(delayMs * 2, SEND_RETRY_MAX_DELAY_MS);
}
}
}
DebugConnection($"SendWithRetryAsync: All {SEND_RETRY_MAX_ATTEMPTS} retry attempts exhausted");
await DisconnectClientAsync(DisconnectReason.Error);
return false;
}
private byte[] Frame(byte[] payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
if (payload.Length > _config.MAX_MESSAGE_SIZE)
{
throw new InvalidOperationException($"Payload size {payload.Length} exceeds maximum message size {_config.MAX_MESSAGE_SIZE}");
}
return _config.MessageFraming == FramingMode.None
? payload
: MessageFrameEncoder.Encode(payload, _config);
}
private byte[] SanitizeReceivedData(byte[] data)
{
try
{
if (data == null)
{
return Array.Empty<byte>();
}
if (data.Length > _config.MAX_MESSAGE_SIZE)
{
throw new InvalidOperationException(
$"Received data size {data.Length} exceeds maximum message size {_config.MAX_MESSAGE_SIZE}");
}
return data;
}
catch (Exception ex)
{
DebugConnection($"SanitizeReceivedData error: {ex.GetType().Name} - {ex.Message}");
return Array.Empty<byte>();
}
}
public async Task<bool> SendNicknameAsync(string nickname)
=> await SendNicknameAsync(nickname, CancellationToken.None).ConfigureAwait(false);
public async Task<bool> SendNicknameAsync(string nickname, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(nickname))
{
return false;
}
var result = await SendAsync($"[NICKNAME]{nickname}[/NICKNAME]", cancellationToken).ConfigureAwait(false);
if (result)
{
Nickname = nickname.Trim();
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
{
ClientId = nickname,
RemoteEndPoint = GetRemoteEndPoint(),
Nickname = nickname
});
}
return result;
}
public async Task<bool> SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
public async Task<bool> SendAsync(string message, CancellationToken cancellationToken)
=> await SendAsync(Encoding.UTF8.GetBytes(message), cancellationToken).ConfigureAwait(false);
public async Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout = null)
=> await SendAndWaitForResponseAsync(data, timeout, CancellationToken.None).ConfigureAwait(false);
public async Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout, CancellationToken cancellationToken)
{
if (data == null || data.Length == 0)
{
DebugConnection("SendAndWaitForResponseAsync: Cannot send null or empty data");
return null;
}
if (!IsConnected)
{
DebugConnection("SendAndWaitForResponseAsync: Not connected");
return null;
}
var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS);
return await ResponseAwaiter.WaitForSingleAsync(
() => SendAsync(data, cancellationToken),
handler => OnDataReceived += handler,
handler => OnDataReceived -= handler,
effectiveTimeout,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(string message, TimeSpan? timeout = null)
=> await SendAndWaitForResponseAsync(Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false);
public async Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(string message, TimeSpan? timeout, CancellationToken cancellationToken)
=> await SendAndWaitForResponseAsync(Encoding.UTF8.GetBytes(message), timeout, cancellationToken).ConfigureAwait(false);
public async Task<DataReceivedEventArgs> SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout = null)
=> await SendNicknameAndWaitForResponseAsync(nickname, timeout, CancellationToken.None).ConfigureAwait(false);
public async Task<DataReceivedEventArgs> SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout, CancellationToken cancellationToken)
{
var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS);
return await ResponseAwaiter.WaitForSingleAsync(
() => SendNicknameAsync(nickname, cancellationToken),
handler => OnDataReceived += handler,
handler => OnDataReceived -= handler,
effectiveTimeout,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task<bool> SendInternalAsync(byte[] data, CancellationToken token)
{
if (data == null || data.Length == 0)
{
DebugConnection("SendInternalAsync: Null or empty data");
return false;
}
if (!IsConnected)
{
return false;
}
if (_config.Protocol == ProtocolType.TCP)
{
if (_stream == null || !_stream.CanWrite)
{
DebugConnection($"SendInternalAsync: Stream is not available for writing for {_config.Host}:{_config.Port}, disconnecting");
await DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
return false;
}
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
if (_config.WriteTimeoutSeconds > 0)
{
cts.CancelAfter(TimeSpan.FromSeconds(_config.WriteTimeoutSeconds));
}
await _streamWriteLock.WaitAsync(cts.Token).ConfigureAwait(false);
try
{
if (_stream == null || !_stream.CanWrite)
{
DebugConnection($"SendInternalAsync: Stream became unavailable after lock acquired for {_config.Host}:{_config.Port}, disconnecting");
await DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
return false;
}
await _stream.WriteAsync(data, 0, data.Length, cts.Token).ConfigureAwait(false);
await _stream.FlushAsync(cts.Token).ConfigureAwait(false);
Interlocked.Add(ref _bytesSent, data.Length);
Interlocked.Increment(ref _messagesSent);
MarkDataSent();
return true;
}
finally
{
_streamWriteLock.Release();
}
}
catch (OperationCanceledException ex)
{
if (token.IsCancellationRequested)
{
return false;
}
DebugConnection($"SendInternalAsync: Write operation canceled for {_config.Host}:{_config.Port}, likely due to timeout or shutdown: {ex.Message}");
RecordError(ex, "Write timeout in TCP send - stream may be unresponsive");
await DisconnectClientAsync(DisconnectReason.Timeout, ex);
return false;
}
catch (SocketException socketEx)
{
DebugConnection($"SendInternalAsync: Socket error while sending TCP data to {_config.Host}:{_config.Port}: {socketEx.SocketErrorCode} - {socketEx.Message}");
RecordError(socketEx, $"Socket error in TCP send: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote host", SocketError.ConnectionAborted => "Connection aborted", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", SocketError.ConnectionRefused => "Connection refused", SocketError.NotConnected => "Socket not connected", SocketError.Shutdown => "Socket shutdown", SocketError.Disconnecting => "Socket disconnecting", _ => "Unknown socket error" }}");
await DisconnectClientAsync(DisconnectReason.Error, socketEx);
return false;
}
catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx)
{
DebugConnection($"SendInternalAsync: Socket IO error while sending TCP data to {_config.Host}:{_config.Port}: {innerSocketEx.SocketErrorCode} - {ioEx.Message}");
RecordError(ioEx, $"Socket IO error in TCP send: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote host", SocketError.ConnectionAborted => "Connection aborted", SocketError.NotConnected => "Socket not connected", _ => "Unknown socket error" }}");
var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted ? DisconnectReason.RemoteClosed : DisconnectReason.Error;
await DisconnectClientAsync(reason, ioEx);
return false;
}
catch (IOException ioEx)
{
DebugConnection($"SendInternalAsync: IO error while sending TCP data to {_config.Host}:{_config.Port}: {ioEx.Message}");
RecordError(ioEx, $"IO error in TCP send: {ioEx.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ioEx);
return false;
}
catch (ObjectDisposedException ex)
{
DebugConnection($"SendInternalAsync: ObjectDisposedException for {_config.Host}:{_config.Port}, stream was likely disposed during reconnection");
RecordError(ex, "Stream disposed during TCP send - possible race condition during reconnection attempt");
if (IsConnected)
{
await DisconnectClientAsync(DisconnectReason.Error, ex).ConfigureAwait(false);
}
return false;
}
catch (Exception ex)
{
DebugConnection($"SendInternalAsync: Exception occurred while sending data to {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Error in TCP send: {ex.GetType().Name} - {ex.Message}");
await DisconnectClientAsync(DisconnectReason.Error, ex);
return false;
}
}
else
{
try
{
if (token.IsCancellationRequested)
{
return false;
}
if (_udpClient != null)
{
await _udpClient.SendAsync(data, data.Length).ConfigureAwait(false);
Interlocked.Add(ref _bytesSent, data.Length);
Interlocked.Increment(ref _messagesSent);
MarkDataSent();
return true;
}
return false;
}
catch (SocketException socketEx)
{
DebugConnection($"SendInternalAsync: Socket error sending UDP data to {_config.Host}:{_config.Port}: {socketEx.SocketErrorCode} - {socketEx.Message}");
RecordError(socketEx, $"Socket error in UDP send: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", _ => "Unknown socket error" }}");
return false;
}
catch (Exception ex)
{
DebugConnection($"SendInternalAsync: Error sending UDP data to {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}");
RecordError(ex, $"Error in UDP send: {ex.GetType().Name} - {ex.Message}");
return false;
}
}
}
}
}
@@ -0,0 +1,163 @@
using EonaCat.Connections.Helpers;
using EonaCat.Connections.ConnectionDiagnostics;
using System.Globalization;
using System.Text;
namespace EonaCat.Connections
{
public partial class NetworkClient
{
public int IdleTimeInSeconds()
{
var idleTime = IdleTime();
return (int)idleTime.TotalSeconds;
}
public int IdleTimeInMinutes()
{
var idleTime = IdleTime();
return (int)idleTime.TotalMinutes;
}
public int IdleTimeInHours()
{
var idleTime = IdleTime();
return (int)idleTime.TotalHours;
}
public int IdleTimeInDays()
{
var idleTime = IdleTime();
return (int)idleTime.TotalDays;
}
public TimeSpan IdleTime()
{
return DateTime.UtcNow - LastActive;
}
public string IdleTimeFormatted(bool includeDays = true, bool includeHours = true, bool includeMinutes = true, bool includeSeconds = true, bool includeMilliseconds = true)
{
return ConnectionTimeFormatter.Format(
IdleTime(),
includeDays,
includeHours,
includeMinutes,
includeSeconds,
includeMilliseconds);
}
public int ConnectedTimeInSeconds()
{
var connectedTime = DateTime.UtcNow - ConnectionTime;
return (int)connectedTime.TotalSeconds;
}
public int ConnectedTimeInMinutes()
{
var connectedTime = DateTime.UtcNow - ConnectionTime;
return (int)connectedTime.TotalMinutes;
}
public int ConnectedTimeInHours()
{
var connectedTime = DateTime.UtcNow - ConnectionTime;
return (int)connectedTime.TotalHours;
}
public int ConnectedTimeInDays()
{
var connectedTime = DateTime.UtcNow - ConnectionTime;
return (int)connectedTime.TotalDays;
}
public TimeSpan ConnectedTime()
{
return DateTime.UtcNow - ConnectionTime;
}
public string ConnectedTimeFormatted(bool includeDays = true, bool includeHours = true, bool includeMinutes = true, bool includeSeconds = true, bool includeMilliseconds = true)
{
return ConnectionTimeFormatter.Format(
ConnectedTime(),
includeDays,
includeHours,
includeMinutes,
includeSeconds,
includeMilliseconds);
}
private string BuildHealthJson()
{
var E = HealthApiServer.JsonEscape;
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"client\"," +
$"\"processName\":{E(HealthApiServer.GetProcessName())}," +
$"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"protocol\":{E(_config.Protocol.ToString())}," +
$"\"isConnected\":{(IsConnected ? "true" : "false")}," +
$"\"isSecure\":{(IsSecure ? "true" : "false")}," +
$"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," +
$"\"uptimeSeconds\":{Uptime.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}," +
$"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}" +
"}";
}
private string BuildStatusJson()
{
var E = HealthApiServer.JsonEscape;
return "{" +
"\"status\":\"ok\"," +
"\"type\":\"client\"," +
$"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," +
$"\"protocol\":{E(_config.Protocol.ToString())}," +
$"\"isConnected\":{(IsConnected ? "true" : "false")}," +
$"\"isSecure\":{(IsSecure ? "true" : "false")}," +
$"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," +
$"\"nickname\":{E(Nickname ?? string.Empty)}," +
$"\"bytesSent\":{BytesSent}," +
$"\"bytesReceived\":{BytesReceived}," +
$"\"messagesSent\":{MessagesSent}," +
$"\"messagesReceived\":{MessagesReceived}," +
$"\"uptimeSeconds\":{Uptime.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}," +
$"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}," +
$"\"lastActiveUtc\":{(LastActive == default ? "null" : E(LastActive.ToString("O")))}," +
$"\"idleTimeSeconds\":{IdleTime().TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}," +
$"\"lastDataSentUtc\":{(LastDataSent == default ? "null" : E(LastDataSent.ToString("O")))}," +
$"\"lastDataReceivedUtc\":{(LastDataReceived == default ? "null" : E(LastDataReceived.ToString("O")))}," +
$"\"disconnectionTimeUtc\":{(DisconnectionTime == default ? "null" : E(DisconnectionTime.ToString("O")))}," +
$"\"isAutoConnectStarted\":{(IsAutoConnectStarted ? "true" : "false")}," +
$"\"totalErrors\":{StatusPage.TotalErrors}," +
$"\"sslErrors\":{StatusPage.SslErrorCount}" +
"}";
}
public string GetConnectionHealthSummary()
{
try
{
var sb = new StringBuilder();
sb.AppendLine($"Connection Status: {(IsConnected ? "Connected" : "Disconnected")}");
sb.AppendLine($"Endpoint: {_config?.Host}:{_config?.Port}");
sb.AppendLine($"Protocol: {_config?.Protocol}");
sb.AppendLine($"Connection Time: {(ConnectionTime != DateTime.MinValue ? ConnectionTime.ToString("O") : "N/A")}");
sb.AppendLine($"Last Activity: {(LastActive != DateTime.MinValue ? LastActive.ToString("O") : "N/A")}");
sb.AppendLine($"Last Pong: {(LastPongReceived != DateTime.MinValue ? LastPongReceived.ToString("O") : "N/A")}");
sb.AppendLine($"Bytes Sent: {BytesSent}");
sb.AppendLine($"Bytes Received: {BytesReceived}");
sb.AppendLine($"Messages Sent: {MessagesSent}");
sb.AppendLine($"Messages Received: {MessagesReceived}");
sb.AppendLine($"Auto-connect Running: {IsAutoConnectStarted}");
sb.AppendLine($"Nickname: {Nickname ?? "N/A"}");
sb.AppendLine($"Encryption: {(IsEncrypted ? "Enabled (AES)" : "Disabled")}");
sb.AppendLine($"SSL: {(_config?.UseSsl ?? false ? "Enabled" : "Disabled")}");
return sb.ToString();
}
catch (Exception ex)
{
return $"Error getting health summary: {ex.GetType().Name} - {ex.Message}";
}
}
}
}
@@ -0,0 +1,282 @@
using System.Text;
namespace EonaCat.Connections.ConnectionDiagnostics
{
public class ConnectionLogger : IDisposable
{
private const long MAX_FILE_SIZE = 10 * 1024 * 1024;
private const int MAX_LOG_FILES = 10;
private const string LOG_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.fff";
private readonly string _logFilePath;
private readonly string _logDirectory;
private readonly string _baseFileName;
private readonly object _lockObject = new object();
private bool _disposed = false;
public ConnectionLogger(bool isServer, string customLogDirectory = null)
{
_logDirectory = string.IsNullOrEmpty(customLogDirectory)
? Path.Combine(AppContext.BaseDirectory, "Logs")
: customLogDirectory;
Directory.CreateDirectory(_logDirectory);
_baseFileName = isServer ? "connection_server" : "connection_client";
_logFilePath = Path.Combine(_logDirectory, $"{_baseFileName}.log");
}
public void LogDisconnection(string clientId, string nickname, string remoteEndPoint, string localEndPoint, string reason, string initiator, Exception exception = null, Dictionary<string, string> additionalContext = null)
{
ThrowIfDisposed();
var message = FormatDisconnectionLog(clientId, nickname, remoteEndPoint, localEndPoint, reason, initiator, exception, additionalContext);
WriteLog(message);
}
public void LogEvent(string eventType, string clientId, string nickname, string remoteEndPoint, string localEndPoint, string message = null)
{
ThrowIfDisposed();
var logMessage = FormatEventLog(eventType, clientId, nickname, remoteEndPoint, localEndPoint, message);
WriteLog(logMessage);
}
public void LogError(string clientId, string remoteEndPoint, string localEndPoint, string errorType, Exception exception, Dictionary<string, string> context = null)
{
ThrowIfDisposed();
var logMessage = FormatErrorLog(clientId, remoteEndPoint, localEndPoint, errorType, exception, context);
WriteLog(logMessage);
}
public void LogSocketError(string clientId, string remoteEndPoint, string localEndPoint, System.Net.Sockets.SocketError? socketError, string errorMessage, Exception exception = null)
{
ThrowIfDisposed();
var logMessage = FormatSocketErrorLog(clientId, remoteEndPoint, localEndPoint, socketError, errorMessage, exception);
WriteLog(logMessage);
}
private string FormatDisconnectionLog(string clientId, string nickname, string remoteEndPoint, string localEndPoint,
string reason, string initiator, Exception exception, Dictionary<string, string> additionalContext)
{
var stringBuilder = new StringBuilder();
var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT);
var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT);
stringBuilder.AppendLine("-------------------------------------------------------------------------------");
stringBuilder.AppendLine($"[DISCONNECTION] Local: {localTimestamp} | UTC: {utcTimestamp}");
stringBuilder.AppendLine("-------------------------------------------------------------------------------");
stringBuilder.AppendLine($" Client ID: {clientId}");
stringBuilder.AppendLine($" Nickname: {(string.IsNullOrEmpty(nickname) ? "[Not Set]" : nickname)}");
stringBuilder.AppendLine($" Remote Endpoint: {remoteEndPoint}");
stringBuilder.AppendLine($" Local Endpoint: {localEndPoint}");
stringBuilder.AppendLine($" Disconnect Reason: {reason}");
stringBuilder.AppendLine($" Initiated By: {initiator}");
if (exception != null)
{
stringBuilder.AppendLine($" Exception Type: {exception.GetType().FullName}");
stringBuilder.AppendLine($" Exception Message: {exception.Message}");
if (!string.IsNullOrEmpty(exception.StackTrace))
{
stringBuilder.AppendLine($" Stack Trace:");
foreach (var line in exception.StackTrace.Split('\n'))
{
if (!string.IsNullOrWhiteSpace(line))
{
stringBuilder.AppendLine($" {line}");
}
}
}
if (exception.InnerException != null)
{
stringBuilder.AppendLine($" Inner Exception: {exception.InnerException.GetType().FullName}: {exception.InnerException.Message}");
}
}
if (additionalContext != null && additionalContext.Count > 0)
{
stringBuilder.AppendLine($" Additional Context:");
foreach (var kvp in additionalContext)
{
stringBuilder.AppendLine($" - {kvp.Key}: {kvp.Value}");
}
}
stringBuilder.AppendLine("-------------------------------------------------------------------------------");
return stringBuilder.ToString();
}
private string FormatEventLog(string eventType, string clientId, string nickname,
string remoteEndPoint, string localEndPoint, string message)
{
var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT);
var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT);
var sb = new StringBuilder();
sb.AppendLine($"[{eventType}] UTC: {utcTimestamp} | Local: {localTimestamp}");
sb.AppendLine($" Client ID: {clientId}, Nickname: {(string.IsNullOrEmpty(nickname) ? "[Not Set]" : nickname)}, Remote: {remoteEndPoint}, Local: {localEndPoint}");
if (!string.IsNullOrEmpty(message))
{
sb.AppendLine($" Details: {message}");
}
return sb.ToString();
}
private string FormatErrorLog(string clientId, string remoteEndPoint, string localEndPoint, string errorType, Exception exception, Dictionary<string, string> context)
{
var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT);
var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT);
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("-------------------------------------------------------------------------------");
stringBuilder.AppendLine($"[ERROR] Local: {localTimestamp} | UTC: {utcTimestamp}");
stringBuilder.AppendLine($" Client ID: {clientId}");
stringBuilder.AppendLine($" Remote Endpoint: {remoteEndPoint}");
stringBuilder.AppendLine($" Local Endpoint: {localEndPoint}");
stringBuilder.AppendLine($" Error Type: {errorType}");
stringBuilder.AppendLine($" Exception: {exception?.GetType().Name}: {exception?.Message}");
if (context != null && context.Count > 0)
{
stringBuilder.AppendLine($" Context:");
foreach (var kvp in context)
{
stringBuilder.AppendLine($" - {kvp.Key}: {kvp.Value}");
}
}
stringBuilder.AppendLine("-------------------------------------------------------------------------------");
return stringBuilder.ToString();
}
private string FormatSocketErrorLog(string clientId, string remoteEndPoint, string localEndPoint, System.Net.Sockets.SocketError? socketError, string errorMessage, Exception exception)
{
var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT);
var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT);
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("-------------------------------------------------------------------------------");
stringBuilder.AppendLine($"[SOCKET_ERROR] Local: {localTimestamp} | UTC: {utcTimestamp}");
stringBuilder.AppendLine($" Client ID: {clientId}");
stringBuilder.AppendLine($" Remote Endpoint: {remoteEndPoint}");
stringBuilder.AppendLine($" Local Endpoint: {localEndPoint}");
if (socketError.HasValue)
{
stringBuilder.AppendLine($" Socket Error: {socketError.Value} ({(int)socketError.Value})");
}
stringBuilder.AppendLine($" Message: {errorMessage}");
if (exception != null)
{
stringBuilder.AppendLine($" Exception: {exception.GetType().Name}: {exception.Message}");
}
stringBuilder.AppendLine("-------------------------------------------------------------------------------");
return stringBuilder.ToString();
}
private void WriteLog(string message)
{
lock (_lockObject)
{
try
{
RotateIfNeeded();
File.AppendAllText(_logFilePath, message + Environment.NewLine);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to write to connection log: {ex.Message}");
}
}
}
private void RotateIfNeeded()
{
try
{
if (!File.Exists(_logFilePath))
{
return;
}
var fileInfo = new FileInfo(_logFilePath);
if (fileInfo.Length >= MAX_FILE_SIZE)
{
var archiveFileName = $"{_baseFileName}_{DateTime.UtcNow:yyyyMMdd_HHmmss}.log";
var archiveFilePath = Path.Combine(_logDirectory, archiveFileName);
if (File.Exists(archiveFilePath))
{
File.Delete(archiveFilePath);
}
File.Move(_logFilePath, archiveFilePath);
CleanupOldLogs();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to rotate log file: {ex.Message}");
}
}
private void CleanupOldLogs()
{
try
{
if (!Directory.Exists(_logDirectory))
{
return;
}
var logFiles = Directory.GetFiles(_logDirectory, $"{_baseFileName}_*.log")
.OrderByDescending(f => File.GetCreationTimeUtc(f))
.ToList();
while (logFiles.Count > MAX_LOG_FILES - 1)
{
try
{
File.Delete(logFiles[logFiles.Count - 1]);
logFiles.RemoveAt(logFiles.Count - 1);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to delete old log file: {ex.Message}");
break;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to cleanup old logs: {ex.Message}");
}
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(ConnectionLogger));
}
}
public void Dispose()
{
_disposed = true;
}
}
}
@@ -0,0 +1,43 @@
namespace EonaCat.Connections.ConnectionDiagnostics
{
internal static class ConnectionTimeFormatter
{
public static string Format(
TimeSpan span,
bool includeDays,
bool includeHours,
bool includeMinutes,
bool includeSeconds,
bool includeMilliseconds)
{
var parts = new List<string>();
if (includeDays)
{
parts.Add($"{(int)span.TotalDays:D2}d");
}
if (includeHours)
{
parts.Add($"{span.Hours:D2}h");
}
if (includeMinutes)
{
parts.Add($"{span.Minutes:D2}m");
}
if (includeSeconds)
{
parts.Add($"{span.Seconds:D2}s");
}
if (includeMilliseconds)
{
parts.Add($"{span.Milliseconds:D3}ms");
}
return string.Join(" ", parts);
}
}
}
@@ -0,0 +1,276 @@
using System.Net;
using System.Net.Sockets;
namespace EonaCat.Connections.ConnectionDiagnostics
{
public class DisconnectionDiagnostics
{
public static string DetermineInitiator(DisconnectReason reason, Exception exception)
{
if (reason == DisconnectReason.LocalClosed ||
reason == DisconnectReason.ClientRequested ||
reason == DisconnectReason.ServerShutdown ||
reason == DisconnectReason.Reconnect ||
reason == DisconnectReason.Forced)
{
return "Local";
}
if (reason == DisconnectReason.RemoteClosed)
{
return "Remote";
}
if (exception != null && exception is SocketException socketEx)
{
return DetermineInitiatorFromSocketError(socketEx.SocketErrorCode);
}
return "Unknown";
}
public static string GetDetailedReasonDescription(DisconnectReason reason, Exception exception)
{
var description = reason switch
{
DisconnectReason.Unknown => "The disconnection reason is unknown",
DisconnectReason.RemoteClosed => "The remote peer closed the connection",
DisconnectReason.LocalClosed => "The local endpoint closed the connection",
DisconnectReason.Timeout => "Connection timeout - no data received within timeout period",
DisconnectReason.Error => "A general error occurred causing disconnection",
DisconnectReason.SSLError => "An SSL/TLS error occurred during secure communication",
DisconnectReason.ServerShutdown => "Server is shutting down",
DisconnectReason.Reconnect => "Disconnection for reconnection purposes",
DisconnectReason.ClientRequested => "The client requested disconnection",
DisconnectReason.Forced => "Connection was forcibly closed",
DisconnectReason.NoPongReceived => "No pong response received to ping - peer may be unresponsive",
DisconnectReason.ProtocolError => "A protocol error occurred in message parsing or handling",
DisconnectReason.BufferOverflow => "Receive buffer overflow - data loss occurred",
DisconnectReason.ConnectionReset => "Connection reset by peer",
DisconnectReason.ConnectionAborted => "Connection was aborted",
DisconnectReason.Refused => "Connection was refused by the peer",
DisconnectReason.NetUnreachable => "Network is unreachable",
DisconnectReason.HostUnreachable => "Host is unreachable",
DisconnectReason.InvalidAddress => "Invalid remote address",
DisconnectReason.AddressInUse => "Address is already in use",
DisconnectReason.AccessDenied => "Access denied - permission issue",
DisconnectReason.ResourceExhausted => "System resource exhaustion (memory, file handles, etc.)",
DisconnectReason.InvalidOperation => "Invalid operation on socket",
DisconnectReason.ShutdownInProgress => "Shutdown is in progress",
DisconnectReason.DataTransmissionError => "Error occurred during data transmission",
DisconnectReason.AesEncryptionError => "AES encryption/decryption error",
_ => $"Disconnection with reason: {reason}"
};
if (exception != null && exception is SocketException socketEx)
{
description += $" [SocketError: {socketEx.SocketErrorCode} ({(int)socketEx.SocketErrorCode})]";
}
return description;
}
public static Dictionary<string, string> AnalyzeSocketException(SocketException socketException)
{
var context = new Dictionary<string, string>();
if (socketException == null)
{
return context;
}
context["SocketErrorCode"] = $"{socketException.SocketErrorCode} ({(int)socketException.SocketErrorCode})";
context["NativeErrorCode"] = socketException.NativeErrorCode.ToString();
context["Message"] = socketException.Message ?? "[No message available]";
context["ErrorCategory"] = CategorizeSocketError(socketException.SocketErrorCode);
var recommendation = GetSocketErrorRecommendation(socketException.SocketErrorCode);
if (!string.IsNullOrEmpty(recommendation))
{
context["Recommendation"] = recommendation;
}
return context;
}
public static Dictionary<string, string> GetEndpointDiagnostics(IPEndPoint endPoint)
{
var context = new Dictionary<string, string>();
if (endPoint == null)
{
context["EndpointInfo"] = "No endpoint information available";
return context;
}
try
{
context["Address"] = endPoint.Address?.ToString() ?? "[Unknown]";
context["Port"] = endPoint.Port.ToString();
context["AddressFamily"] = endPoint.AddressFamily.ToString();
context["IsLoopback"] = (endPoint.Address != null ? IPAddress.IsLoopback(endPoint.Address) : false).ToString();
context["IsIPv4"] = (endPoint.AddressFamily == AddressFamily.InterNetwork).ToString();
context["IsIPv6"] = (endPoint.AddressFamily == AddressFamily.InterNetworkV6).ToString();
}
catch (Exception ex)
{
context["Error"] = $"Failed to extract endpoint diagnostics: {ex.Message}";
}
return context;
}
private static string CategorizeSocketError(SocketError errorCode)
{
return errorCode switch
{
SocketError.ConnectionReset or
SocketError.ConnectionAborted or
SocketError.ConnectionRefused or
SocketError.NotConnected or
SocketError.Shutdown or
SocketError.Disconnecting => "Connection/State Error",
SocketError.TimedOut => "Timeout Error",
SocketError.NetworkUnreachable or
SocketError.HostUnreachable or
SocketError.NetworkDown or
SocketError.HostDown => "Network Error",
SocketError.AddressAlreadyInUse or
SocketError.AddressNotAvailable => "Address Error",
SocketError.AccessDenied => "Permission Error",
SocketError.NoBufferSpaceAvailable or
SocketError.TooManyOpenSockets => "Resource Error",
SocketError.ProtocolNotSupported or
SocketError.ProtocolOption or
SocketError.ProtocolType or
SocketError.InvalidArgument => "Protocol/Argument Error",
SocketError.OperationNotSupported or
SocketError.OperationAborted => "Operation Error",
_ => "Other/Unknown Error"
};
}
private static string GetSocketErrorRecommendation(SocketError errorCode)
{
return errorCode switch
{
SocketError.ConnectionReset => "Connection was forcibly closed by peer. Check if peer crashed or network was interrupted.",
SocketError.ConnectionRefused => "Peer is not listening on this port. Verify peer is running and port is correct.",
SocketError.TimedOut => "No response from peer within timeout period. Check network connectivity and peer performance.",
SocketError.NetworkUnreachable => "Network path doesn't exist. Check routing and firewall rules.",
SocketError.HostUnreachable => "Cannot reach the host. Verify IP address is correct and host is online.",
SocketError.AddressAlreadyInUse => "Port is already in use. Wait for TIME_WAIT to expire or use different port.",
SocketError.AccessDenied => "Insufficient permissions. May need elevated privileges or firewall reconfiguration.",
SocketError.NoBufferSpaceAvailable => "System buffer exhausted. Consider reducing traffic or increasing system buffers.",
SocketError.TooManyOpenSockets => "Too many open connections. Close idle connections or increase system limits.",
SocketError.ProtocolNotSupported => "Protocol is not supported by system. Verify socket creation parameters.",
_ => null
};
}
private static string DetermineInitiatorFromSocketError(SocketError errorCode)
{
return errorCode switch
{
SocketError.ConnectionReset or
SocketError.Shutdown or
SocketError.Disconnecting => "Remote",
SocketError.TimedOut or
SocketError.NoBufferSpaceAvailable or
SocketError.TooManyOpenSockets or
SocketError.NetworkDown or
SocketError.NetworkUnreachable => "Local",
SocketError.ConnectionRefused or
SocketError.HostUnreachable => "Remote",
_ => "Unknown"
};
}
public static Dictionary<string, string> CreateDisconnectionSummary(
string clientId,
string nickname,
IPEndPoint remoteEndPoint,
DisconnectReason reason,
Exception exception,
TimeSpan? connectionDuration = null)
{
var summary = new Dictionary<string, string>
{
{ "ClientId", string.IsNullOrEmpty(clientId) ? "[Unknown]" : clientId },
{ "Nickname", string.IsNullOrEmpty(nickname) ? "[Not Set]" : nickname },
{ "RemoteEndPoint", remoteEndPoint?.ToString() ?? "[Unknown]" },
{ "DisconnectReason", reason.ToString() },
{ "ReasonDescription", GetDetailedReasonDescription(reason, exception) },
{ "Initiator", DetermineInitiator(reason, exception) },
{ "Timestamp", DateTime.UtcNow.ToString("O") }
};
if (connectionDuration.HasValue)
{
summary["ConnectionDuration"] = FormatTimeSpan(connectionDuration.Value);
}
if (exception != null)
{
summary["ExceptionType"] = exception.GetType().Name;
summary["ExceptionMessage"] = exception.Message ?? "[Exception message not available]";
if (exception is SocketException socketEx)
{
var socketContext = AnalyzeSocketException(socketEx);
foreach (var kvp in socketContext)
{
summary[$"Socket_{kvp.Key}"] = kvp.Value;
}
}
}
if (remoteEndPoint != null)
{
var endpointContext = GetEndpointDiagnostics(remoteEndPoint);
foreach (var kvp in endpointContext)
{
summary[$"RemoteEndpoint_{kvp.Key}"] = kvp.Value;
}
}
return summary;
}
private static string FormatTimeSpan(TimeSpan duration)
{
if (duration.TotalHours >= 1)
{
return $"{duration.Hours}h {duration.Minutes}m {duration.Seconds}s";
}
if (duration.TotalMinutes >= 1)
{
return $"{duration.Minutes}m {duration.Seconds}s";
}
if (duration.TotalSeconds >= 1)
{
return $"{duration.TotalSeconds:F2}s";
}
return $"{duration.TotalMilliseconds:F0}ms";
}
}
}
@@ -0,0 +1,53 @@
using EonaCat.Connections.ConnectionDiagnostics;
namespace EonaCat.Connections
{
public static class ConnectionLogManager
{
private static ConnectionLogger _serverLogger;
private static ConnectionLogger _clientLogger;
private static readonly object _lockObject = new object();
public static ConnectionLogger GetServerLogger()
{
if (_serverLogger == null)
{
lock (_lockObject)
{
if (_serverLogger == null)
{
_serverLogger = new ConnectionLogger(isServer: true);
}
}
}
return _serverLogger;
}
public static ConnectionLogger GetClientLogger()
{
if (_clientLogger == null)
{
lock (_lockObject)
{
if (_clientLogger == null)
{
_clientLogger = new ConnectionLogger(isServer: false);
}
}
}
return _clientLogger;
}
public static void Dispose()
{
lock (_lockObject)
{
_serverLogger?.Dispose();
_clientLogger?.Dispose();
_serverLogger = null;
_clientLogger = null;
}
}
}
}
@@ -0,0 +1,54 @@
using EonaCat.Connections.EventArguments;
using ConnectorErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.Contracts
{
public interface IConnectorClient : IDisposable, IAsyncDisposable
{
event EventHandler<ConnectionEventArgs> OnConnected;
event EventHandler<ConnectionEventArgs> OnNicknameSend;
event EventHandler<DataReceivedEventArgs> OnDataReceived;
event EventHandler<ConnectionEventArgs> OnDisconnected;
event EventHandler<ConnectorErrorEventArgs> OnSslError;
event EventHandler<ConnectorErrorEventArgs> OnEncryptionError;
event EventHandler<ConnectorErrorEventArgs> OnGeneralError;
event EventHandler<ConnectorErrorEventArgs> OnSocketError;
event EventHandler<PingEventArgs> OnPingResponse;
event EventHandler<PingEventArgs> OnPongResponse;
bool IsConnected { get; }
bool IsSecure { get; }
bool IsEncrypted { get; }
bool IsTcp { get; }
string IpAddress { get; }
int Port { get; }
string Nickname { get; }
DateTime ConnectionTime { get; }
TimeSpan Uptime { get; }
DateTime LastActive { get; }
long BytesSent { get; }
long BytesReceived { get; }
long MessagesSent { get; }
long MessagesReceived { get; }
Task<bool> ConnectAsync();
Task<bool> WaitForConnectedAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default);
Task DisconnectAsync();
Task DisconnectDueTimeoutAsync();
Task<bool> SendAsync(byte[] data);
Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken);
Task<bool> SendAsync(string message);
Task<bool> SendAsync(string message, CancellationToken cancellationToken);
Task<bool> SendNicknameAsync(string nickname);
Task<bool> SendNicknameAsync(string nickname, CancellationToken cancellationToken);
Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout = null);
Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout, CancellationToken cancellationToken);
Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(string message, TimeSpan? timeout = null);
Task<DataReceivedEventArgs> SendAndWaitForResponseAsync(string message, TimeSpan? timeout, CancellationToken cancellationToken);
Task<DataReceivedEventArgs> SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout = null);
Task<DataReceivedEventArgs> SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout, CancellationToken cancellationToken);
TimeSpan IdleTime();
TimeSpan ConnectedTime();
string GetConnectionHealthSummary();
}
}
@@ -0,0 +1,46 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Models;
using ConnectorErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections.Contracts
{
public interface IConnectorServer : IDisposable
{
event EventHandler<ConnectionEventArgs> OnConnected;
event EventHandler<ConnectionEventArgs> OnConnectedWithNickname;
event EventHandler<DataReceivedEventArgs> OnDataReceived;
event EventHandler<ConnectionEventArgs> OnDisconnected;
event EventHandler<ConnectorErrorEventArgs> OnSslError;
event EventHandler<ConnectorErrorEventArgs> OnEncryptionError;
event EventHandler<ConnectorErrorEventArgs> OnGeneralError;
event EventHandler<ConnectorErrorEventArgs> OnSocketError;
event EventHandler<ClientMissingEventArgs> OnClientMissing;
event EventHandler<PingEventArgs> OnClientPingResponse;
event EventHandler<PingEventArgs> OnPongMissed;
bool IsStarted { get; }
bool IsSecure { get; }
bool IsEncrypted { get; }
ProtocolType Protocol { get; }
string IpAddress { get; }
int Port { get; }
int ActiveConnections { get; }
int MaxConnections { get; }
Stats GetStats();
Dictionary<string, object> GetSecurityMetrics();
Dictionary<string, Connection> GetClients();
List<Connection> GetClient(string clientId);
Task StartAsync();
Task StopAsync();
Task<bool> SendToClientAsync(string clientId, byte[] data);
Task<bool> SendToClientAsync(string clientId, string message);
Task<bool> SendFromClientToClientAsync(string fromClientId, string toClientId, byte[] data);
Task<bool> SendFromClientToClientAsync(string fromClientId, string toClientId, string message);
Task<bool> BroadcastAsync(byte[] data);
Task<bool> BroadcastAsync(string message);
Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.Unknown, Exception? exception = null);
void SetSeparator(string separator);
void SetSeparator(byte[] separator);
}
}
+16 -2
View File
@@ -1,10 +1,9 @@
namespace EonaCat.Connections
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public enum DisconnectReason
{
Unknown,
RemoteClosed,
LocalClosed,
@@ -17,5 +16,20 @@
Forced,
NoPongReceived,
ProtocolError,
BufferOverflow,
ConnectionReset,
ConnectionAborted,
Refused,
NetUnreachable,
HostUnreachable,
InvalidAddress,
AddressInUse,
AccessDenied,
ResourceExhausted,
InvalidOperation,
ShutdownInProgress,
DataTransmissionError,
AesEncryptionError,
}
}
+37 -15
View File
@@ -1,30 +1,44 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0; net48; net8.0</TargetFrameworks>
<TargetFrameworks>net481; net8.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>EonaCat.Connections</Title>
<Company>EonaCat (Jeroen Saey)</Company>
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<Company>EonaCat</Company>
<Copyright>Jeroen Saey</Copyright>
<PackageReadmeFile>readme.md</PackageReadmeFile>
<PackageId>EonaCat.Connections</PackageId>
<Version>1.1.2</Version>
<Authors>EonaCat (Jeroen Saey)</Authors>
<Version>1.0.0</Version>
<Authors>Jeroen Saey</Authors>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageIcon>EonaCat.png</PackageIcon>
<PackageProjectUrl>https://git.saey.me/EonaCat/EonaCat.Connections</PackageProjectUrl>
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.Connections</RepositoryUrl>
<Description>EonaCat.Connections for TCP/UDP client/servers</Description>
<ApplicationIcon>icon.ico</ApplicationIcon>
<PackageIcon>icon.png</PackageIcon>
</PropertyGroup>
<ItemGroup>
<Content Include="EonaCat.ico" />
<EmbeddedResource Include="Helpers\TrafficDashboard.html" />
<Compile Remove="Extensions\**" />
<Compile Remove="Logging\**" />
<EmbeddedResource Remove="Extensions\**" />
<EmbeddedResource Remove="Logging\**" />
<None Remove="Extensions\**" />
<None Remove="Logging\**" />
</ItemGroup>
<ItemGroup>
<None Include="..\EonaCat.png">
<Content Remove="C:\Users\jesa\.nuget\packages\eonacat.json\2.0.6\contentFiles\any\net48\Monikers.imagemanifest" />
</ItemGroup>
<ItemGroup>
<Content Include="icon.ico" />
</ItemGroup>
<ItemGroup>
<None Include="..\icon.png">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
@@ -39,11 +53,19 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="EonaCat.Json" Version="2.2.3" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="10.0.9" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="10.0.9" />
<PackageReference Include="System.Buffers" Version="4.6.1" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.6.3" />
<PackageReference Include="EonaCat.Json" Version="2.2.5" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Remove="C:\Users\jesa\AppData\Roaming\SonarLint for Visual Studio\.global\csharp\SonarLint.xml" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Remove="C:\Users\jesa\AppData\Roaming\SonarLint for Visual Studio\.global\csharp\SonarLint.xml" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Remove="C:\Users\jesa\AppData\Roaming\SonarLint for Visual Studio\.global\csharp\SonarLint.xml" />
</ItemGroup>
</Project>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

@@ -0,0 +1,9 @@
namespace EonaCat.Connections.EventArguments
{
public class ClientMissingEventArgs : EventArgs
{
public string ClientId { get; internal set; }
public DateTime Timestamp { get; internal set; } = DateTime.Now;
public byte[] Data { get; internal set; }
}
}
@@ -1,9 +1,6 @@
using System.Net;
using System.Net.Sockets;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
namespace EonaCat.Connections.EventArguments
{
public class ConnectionEventArgs : EventArgs
@@ -15,6 +12,14 @@ namespace EonaCat.Connections.EventArguments
public Exception Exception { get; set; }
public bool HasException => Exception != null;
public string Initiator { get; set; }
public string ReasonDetails { get; set; }
public TimeSpan? ConnectionDuration { get; set; }
public Dictionary<string, string> DiagnosticContext { get; set; }
public bool IsLocalDisconnect =>
Reason == DisconnectReason.LocalClosed
|| Reason == DisconnectReason.Timeout
@@ -46,18 +51,31 @@ namespace EonaCat.Connections.EventArguments
switch (socketException.SocketErrorCode)
{
case SocketError.ConnectionReset:
return DisconnectReason.ConnectionReset;
case SocketError.ConnectionAborted:
return DisconnectReason.ConnectionAborted;
case SocketError.Shutdown:
case SocketError.Disconnecting:
return DisconnectReason.RemoteClosed;
case SocketError.TimedOut:
return DisconnectReason.Timeout;
case SocketError.NetworkDown:
case SocketError.NetworkReset:
case SocketError.NetworkUnreachable:
return DisconnectReason.Error;
return DisconnectReason.NetUnreachable;
case SocketError.HostUnreachable:
return DisconnectReason.HostUnreachable;
case SocketError.ConnectionRefused:
return DisconnectReason.Refused;
case SocketError.AddressAlreadyInUse:
return DisconnectReason.AddressInUse;
case SocketError.AccessDenied:
return DisconnectReason.AccessDenied;
case SocketError.NoBufferSpaceAvailable:
case SocketError.TooManyOpenSockets:
return DisconnectReason.ResourceExhausted;
case SocketError.InvalidArgument:
return DisconnectReason.InvalidOperation;
default:
return DisconnectReason.Error;
}
@@ -1,9 +1,6 @@
using System.Net;
using System.Text;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
namespace EonaCat.Connections
{
public class DataReceivedEventArgs : EventArgs
@@ -1,8 +1,5 @@
namespace EonaCat.Connections.EventArguments
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class ErrorEventArgs : EventArgs
{
public string ClientId { get; set; }
@@ -1,30 +0,0 @@
using System.Net;
namespace EonaCat.Connections.EventArguments
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class IdleClientEventArgs : EventArgs
{
public IdleClientEventArgs() { }
public IdleClientEventArgs(double idleTimeoutSeconds, NetworkClient networkClient, string message)
{
IdleTimeoutSeconds = idleTimeoutSeconds;
NetworkClient = networkClient;
Message = message;
}
public double IdleTimeoutSeconds { get; set; }
public NetworkClient? NetworkClient { get; set; }
public string? ClientId { get; set; }
public string? Nickname { get; set; }
public IPEndPoint? RemoteEndPoint { get; set; }
public double IdleTimeSeconds { get; set; }
public bool HasClient => NetworkClient != null;
public bool IsIdle => IdleTimeoutSeconds > 0 || IdleTimeSeconds > 0;
public bool HasMessage => !string.IsNullOrEmpty(Message);
public string? Message { get; set; }
}
}
@@ -1,24 +0,0 @@
using EonaCat.Connections.Models;
namespace EonaCat.Connections.EventArguments
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class IdleEventArgs : EventArgs
{
public IdleEventArgs(double idleTimeoutSeconds, Connection connection, string message)
{
IdleTimeoutSeconds = idleTimeoutSeconds;
Connection = connection;
Message = message;
}
public double IdleTimeoutSeconds { get; }
public Connection Connection { get; }
public bool HasConnection => Connection != null;
public bool IsIdle => IdleTimeoutSeconds > 0;
public bool HasMessage => !string.IsNullOrEmpty(Message);
public string Message { get; }
}
}
@@ -2,9 +2,6 @@
namespace EonaCat.Connections.EventArguments
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class PingEventArgs : EventArgs
{
public string Id { get; set; }
@@ -0,0 +1,128 @@
using System.Net;
namespace EonaCat.Connections.Framing
{
internal static class MessageFrameDecoder
{
public static bool TryReadLengthPrefixed(MemoryStream stream, int prefixSize, bool useBigEndian, double maxMessageBytes, out byte[]? message)
{
message = null;
var buffer = stream.GetBuffer();
var bufferedLength = (int)stream.Length;
if (bufferedLength < prefixSize)
{
return false;
}
var messageLengthValue = ParseLengthPrefix(buffer, prefixSize, useBigEndian);
if (messageLengthValue <= 0 || messageLengthValue > maxMessageBytes)
{
throw new ProtocolViolationException($"Declared message length {messageLengthValue} is invalid or exceeds max allowed {maxMessageBytes} bytes.");
}
var messageLength = (int)messageLengthValue;
if (bufferedLength - prefixSize < messageLength)
{
return false;
}
message = new byte[messageLength];
Buffer.BlockCopy(buffer, prefixSize, message, 0, messageLength);
RemoveConsumedBytes(stream, prefixSize + messageLength);
return true;
}
public static bool TryReadDelimited(MemoryStream stream, byte[] delimiter, double maxMessageBytes, out byte[]? message)
{
message = null;
if (delimiter == null || delimiter.Length == 0)
{
throw new ProtocolViolationException("Delimiter framing requires a non-empty delimiter.");
}
var buffer = stream.GetBuffer();
var bufferedLength = (int)stream.Length;
var delimiterIndex = IndexOf(buffer, bufferedLength, delimiter);
if (delimiterIndex < 0)
{
if (bufferedLength > maxMessageBytes + delimiter.Length - 1)
{
throw new ProtocolViolationException($"Delimited message exceeds the maximum allowed {maxMessageBytes} bytes.");
}
return false;
}
if (delimiterIndex > maxMessageBytes)
{
throw new ProtocolViolationException($"Delimited message length {delimiterIndex} exceeds the maximum allowed {maxMessageBytes} bytes.");
}
message = new byte[delimiterIndex];
Buffer.BlockCopy(buffer, 0, message, 0, delimiterIndex);
RemoveConsumedBytes(stream, delimiterIndex + delimiter.Length);
return true;
}
public static long ParseLengthPrefix(byte[] buffer, int length, bool useBigEndian)
{
if (buffer == null || buffer.Length == 0)
{
throw new ArgumentNullException(nameof(buffer));
}
if (length < 1 || length > 8 || length > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), "Length must be between 1 and 8 bytes and fit in the buffer.");
}
long value = 0;
for (var index = 0; index < length; index++)
{
value = useBigEndian
? (value << 8) | buffer[index]
: value | (long)buffer[index] << (8 * index);
}
return value;
}
private static int IndexOf(byte[] buffer, int length, byte[] delimiter)
{
if (length < delimiter.Length)
{
return -1;
}
for (var index = 0; index <= length - delimiter.Length; index++)
{
var matches = true;
for (var delimiterIndex = 0; delimiterIndex < delimiter.Length; delimiterIndex++)
{
if (buffer[index + delimiterIndex] != delimiter[delimiterIndex])
{
matches = false;
break;
}
}
if (matches)
{
return index;
}
}
return -1;
}
private static void RemoveConsumedBytes(MemoryStream stream, int consumedBytes)
{
var buffer = stream.GetBuffer();
var remaining = (int)stream.Length - consumedBytes;
Buffer.BlockCopy(buffer, consumedBytes, buffer, 0, remaining);
stream.SetLength(remaining);
stream.Position = remaining;
}
}
}
@@ -0,0 +1,109 @@
using EonaCat.Connections.Models;
namespace EonaCat.Connections.Framing
{
internal static class MessageFrameEncoder
{
public static byte[] Encode(byte[] payload, Configuration configuration)
{
var result = new byte[GetEncodedLength(payload, configuration)];
Write(result, payload, configuration);
return result;
}
public static int GetEncodedLength(byte[] payload, Configuration configuration)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
return checked(payload.Length + GetFramingOverhead(configuration));
}
public static int Write(byte[] buffer, byte[] payload, Configuration configuration)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
var requiredLength = GetEncodedLength(payload, configuration);
if (buffer.Length < requiredLength)
{
throw new InvalidOperationException("Buffer is too small for the framed message.");
}
var offset = 0;
if (configuration.MessageFraming == FramingMode.LengthPrefixed)
{
WriteLengthPrefix(buffer, payload.Length, configuration.LengthPrefixedLength, configuration.UseBigEndian);
offset = configuration.LengthPrefixedLength;
}
Buffer.BlockCopy(payload, 0, buffer, offset, payload.Length);
offset += payload.Length;
if (configuration.MessageFraming == FramingMode.Delimiter && configuration.Delimiter?.Length > 0)
{
Buffer.BlockCopy(configuration.Delimiter, 0, buffer, offset, configuration.Delimiter.Length);
offset += configuration.Delimiter.Length;
}
return offset;
}
private static int GetFramingOverhead(Configuration configuration)
{
return configuration.MessageFraming switch
{
FramingMode.LengthPrefixed => ValidatePrefixSize(configuration.LengthPrefixedLength),
FramingMode.Delimiter => configuration.Delimiter?.Length ?? 0,
_ => 0
};
}
private static int ValidatePrefixSize(int prefixSize)
{
if (prefixSize < 1 || prefixSize > sizeof(long))
{
throw new ArgumentOutOfRangeException(nameof(prefixSize), "Length prefix must contain between 1 and 8 bytes.");
}
return prefixSize;
}
private static void WriteLengthPrefix(byte[] buffer, int payloadLength, int prefixSize, bool useBigEndian)
{
ValidatePrefixSize(prefixSize);
var maxLength = prefixSize == sizeof(long) ? long.MaxValue : (1L << (prefixSize * 8)) - 1;
if (payloadLength > maxLength)
{
throw new InvalidOperationException("Data length exceeds length prefix capacity.");
}
long remainingLength = payloadLength;
for (var index = 0; index < prefixSize; index++)
{
var targetIndex = useBigEndian ? prefixSize - 1 - index : index;
buffer[targetIndex] = (byte)(remainingLength & 0xFF);
remainingLength >>= 8;
}
}
}
}
+1 -20
View File
@@ -3,29 +3,21 @@ using System.Text;
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public static class AesKeyExchange
{
// 256-bit salt
private const int _saltSize = 32;
// 128-bit IV
private const int _ivSize = 16;
// 256-bit AES key
private const int _aesKeySize = 32;
// 256-bit HMAC key (key confirmation)
private const int _hmacKeySize = 32;
// PBKDF2 iterations
private const int _iterations = 800_000;
private static readonly byte[] KeyConfirmationLabel = Encoding.UTF8.GetBytes("KEYCONFIRMATION");
// AES block size for PKCS7 padding
public static int MaxEncryptionOverhead => 16;
public static Task<byte[]> EncryptDataAsync(byte[] data, int length, Aes aes)
@@ -62,14 +54,12 @@ namespace EonaCat.Connections.Helpers
var salt = RandomBytes(_saltSize);
var iv = RandomBytes(_ivSize);
// Derive AES key and HMAC key (for key confirmation)
var keyMaterial = DeriveKey(password, salt, _aesKeySize + _hmacKeySize);
var aesKey = new byte[_aesKeySize];
var hmacKey = new byte[_hmacKeySize];
Buffer.BlockCopy(keyMaterial, 0, aesKey, 0, _aesKeySize);
Buffer.BlockCopy(keyMaterial, _aesKeySize, hmacKey, 0, _hmacKeySize);
// Compute key confirmation HMAC = HMAC(hmacKey, "KEYCONFIRM" || salt || iv)
byte[] keyConfirm;
using (var h = new HMACSHA256(hmacKey))
{
@@ -79,13 +69,11 @@ namespace EonaCat.Connections.Helpers
keyConfirm = h.Hash;
}
// Send: salt, iv, keyConfirm (each length-prefixed 4-byte big-endian)
await WriteWithLengthAsync(stream, salt).ConfigureAwait(false);
await WriteWithLengthAsync(stream, iv).ConfigureAwait(false);
await WriteWithLengthAsync(stream, keyConfirm).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
// Configure AES and return
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
@@ -200,17 +188,10 @@ namespace EonaCat.Connections.Helpers
private static byte[] DeriveKey(string password, byte[] salt, int size)
{
#if NET472_OR_GREATER || NET8_0_OR_GREATER
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, _iterations, HashAlgorithmName.SHA256))
{
return pbkdf2.GetBytes(size);
}
#else
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, _iterations))
{
return pbkdf2.GetBytes(size);
}
#endif
}
private static byte[] RandomBytes(int total)
@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace EonaCat.Connections.Helpers
{
public static class CertificateHelper
{
public static event EventHandler<string> OnError;
public static void CheckCertificate(HttpWebRequest request)
{
//TODO: As selfSigned certificates are not working and hang the client (for now return true)
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
}
public static void InstallCertificate(X509Certificate2 certificate, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.LocalMachine)
{
using (X509Store store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();
}
}
public static void RemoveCertificate(X509Certificate2 certificate, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.LocalMachine)
{
using (X509Store store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadWrite);
store.Remove(certificate);
store.Close();
}
}
private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
//return sslPolicyErrors == SslPolicyErrors.None;
}
public static X509Certificate2 LoadFromFile(string certificatePath, string certificatePassword = null)
{
if (!string.IsNullOrWhiteSpace(certificatePassword))
{
return new X509Certificate2(certificatePath, certificatePassword);
}
else
{
return new X509Certificate2(certificatePath);
}
}
public static X509Certificate2 GetCertificate(string certificatePath = null, string certificatePassword = null, string certificateThumbprint = null, string privateKeyPath = null)
{
X509Certificate2 certificate = null;
try
{
if (!string.IsNullOrWhiteSpace(certificatePath))
{
var extension = Path.GetExtension(certificatePath)?.ToLower();
if (extension == ".pfx" || extension == ".p12")
{
// PFX/P12 file loading (supports encrypted private keys)
certificate = LoadFromFile(certificatePath, certificatePassword);
}
else if (extension == ".cer" || extension == ".crt")
{
// CER/CRT file loading (only the certificate, no private key)
certificate = LoadFromFile(certificatePath, certificatePassword);
}
else if (extension == ".pem")
{
// PEM file loading (supports both certificate and private key)
certificate = LoadPemCertificate(certificatePath, certificatePassword);
}
else
{
OnError?.Invoke(null, $"Unsupported certificate file format: {extension}");
return null;
}
if (certificate == null)
{
OnError?.Invoke(null, "Failed to load the certificate");
return null;
}
// If a private key is supplied separately, load and attach it
if (!string.IsNullOrWhiteSpace(privateKeyPath))
{
var privateKey = LoadPrivateKeyFromPem(privateKeyPath);
if (privateKey != null)
{
certificate = certificate.CopyWithPrivateKey(privateKey);
}
}
}
else if (!string.IsNullOrWhiteSpace(certificateThumbprint))
{
certificate = LoadFromKeyStore(valueToFind: certificateThumbprint);
certificate ??= LoadFromKeyStore(valueToFind: certificateThumbprint, storeLocation: StoreLocation.CurrentUser);
}
}
catch (Exception ex)
{
OnError?.Invoke(null, ex.Message);
}
return certificate;
}
public static X509Certificate2 LoadPemCertificate(string certFilePath, string password)
{
try
{
var certBytes = File.ReadAllBytes(certFilePath);
X509Certificate2 cert = null;
string certText = Encoding.UTF8.GetString(certBytes);
if (certText.Contains("BEGIN CERTIFICATE"))
{
// Certificate only
cert = new X509Certificate2(certBytes);
}
else if (certText.Contains("BEGIN PRIVATE KEY") || certText.Contains("BEGIN ENCRYPTED PRIVATE KEY"))
{
// Initialize certificate with private key
cert = new X509Certificate2(certBytes);
cert = cert.CopyWithPrivateKey(LoadPrivateKeyFromPem(certFilePath));
}
return cert;
}
catch (Exception ex)
{
OnError?.Invoke(null, $"Error loading PEM certificate: {ex.Message}");
return null;
}
}
public static string ExtractPrivateKeyFromPem(string pemFilePath)
{
try
{
string pemContents = File.ReadAllText(pemFilePath);
// Strip out the header/footer of the private key section
string privateKeyPem = pemContents
.Replace("-----BEGIN PRIVATE KEY-----", "")
.Replace("-----END PRIVATE KEY-----", "")
.Replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "")
.Replace("-----END ENCRYPTED PRIVATE KEY-----", "")
.Trim();
return privateKeyPem;
}
catch (Exception ex)
{
OnError?.Invoke(null, $"Error extracting private key from PEM: {ex.Message}");
return null;
}
}
public static RSA LoadPrivateKeyFromPem(string privateKeyPath)
{
try
{
if (string.IsNullOrEmpty(privateKeyPath))
{
OnError?.Invoke(null, "Please specify the private key file path");
return null;
}
// PEM might have private key, extract it
string keyText = ExtractPrivateKeyFromPem(privateKeyPath);
if (string.IsNullOrWhiteSpace(keyText))
{
OnError?.Invoke(null, "Invalid or empty private key content.");
return null;
}
// Load the private key
RSA privateKey = null;
#if NET48_OR_GREATER
// This is a workaround for .NET Framework, as it does not support encrypted private keys
// You may need BouncyCastle here for .NET Framework to parse encrypted private keys.
// Below is commented as it's unnecessary for .NET 6.0 and greater
/*
using (var reader = new StringReader(keyText))
{
var pemReader = new PemReader(reader);
var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
privateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private);
}
*/
#endif
#if NET6_0_OR_GREATER
// For .NET 6.0 and higher, you can directly load the private key with ImportFromPem
privateKey = RSA.Create();
try
{
privateKey.ImportFromPem(keyText.ToCharArray());
}
catch (CryptographicException ex)
{
OnError?.Invoke(null, $"Error importing private key: {ex.Message}");
return null;
}
#endif
return privateKey;
}
catch (Exception ex)
{
OnError?.Invoke(null, $"Error loading private key: {ex.Message}");
return null;
}
}
public static X509Certificate2 LoadFromKeyStore(StoreName storeName = StoreName.My, X509FindType findType = X509FindType.FindByThumbprint, string valueToFind = null, StoreLocation storeLocation = StoreLocation.LocalMachine, bool onlyGetValidCertificates = false)
{
// Open the certificate store
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
try
{
if (valueToFind == null)
{
OnError?.Invoke(null, "Please specify the value to search for");
return null;
}
// Find the certificate
X509Certificate2Collection certificates = store.Certificates.Find(
findType,
valueToFind,
onlyGetValidCertificates);
if (certificates.Count > 0)
{
X509Certificate2 certificate = certificates[0];
return certificate;
}
else
{
OnError?.Invoke(null, $"The certificate '{valueToFind}' was not found");
return null;
}
}
finally
{
// Close the store
store.Close();
}
}
}
}
@@ -0,0 +1,169 @@
namespace EonaCat.Connections.Helpers
{
public static class HandlingHelpers
{
public static void SafeInvokeEventHandler<TEventArgs>(EventHandler<TEventArgs> handler, object sender, TEventArgs args, string eventName, Action<string> logAction = null) where TEventArgs : EventArgs
{
if (handler == null)
{
return;
}
try
{
handler.Invoke(sender, args);
}
catch (Exception ex)
{
string errorMsg = $"Exception in event handler for '{eventName}': {ex.GetType().Name} - {ex.Message}";
logAction?.Invoke(errorMsg);
System.Diagnostics.Debug.WriteLine(errorMsg);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
public static void SafeInvokeEventHandler(EventHandler handler, object sender, EventArgs args, string eventName, Action<string> logAction = null)
{
if (handler == null)
{
return;
}
try
{
handler.Invoke(sender, args);
}
catch (Exception ex)
{
string errorMsg = $"Exception in event handler for '{eventName}': {ex.GetType().Name} - {ex.Message}";
logAction?.Invoke(errorMsg);
System.Diagnostics.Debug.WriteLine(errorMsg);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
public static Task SafeFireAndForgetTaskAsync(Func<Task> asyncAction, string taskName, Action<string> logAction = null)
{
if (asyncAction == null)
{
throw new ArgumentNullException(nameof(asyncAction));
}
return Task.Run(async () =>
{
try
{
await asyncAction();
}
catch (OperationCanceledException)
{
string msg = $"Fire-and-forget task '{taskName}' was cancelled";
System.Diagnostics.Debug.WriteLine(msg);
}
catch (Exception ex)
{
string errorMsg = $"Unobserved exception in fire-and-forget task '{taskName}': {ex.GetType().Name} - {ex.Message}";
logAction?.Invoke(errorMsg);
System.Diagnostics.Debug.WriteLine(errorMsg);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
});
}
public static Task SafeFireAndForgetTaskAsync(Action action, string taskName, Action<string> logAction = null)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
return Task.Run(() =>
{
try
{
action();
}
catch (OperationCanceledException)
{
string msg = $"Fire-and-forget task '{taskName}' was cancelled";
System.Diagnostics.Debug.WriteLine(msg);
}
catch (Exception ex)
{
string errorMsg = $"Unobserved exception in fire-and-forget task '{taskName}': {ex.GetType().Name} - {ex.Message}";
logAction?.Invoke(errorMsg);
System.Diagnostics.Debug.WriteLine(errorMsg);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
});
}
public static void SafeDispose(IDisposable disposable, string objectName = "object", Action<string> logAction = null)
{
if (disposable == null)
{
return;
}
try
{
disposable?.Dispose();
}
catch (Exception ex)
{
string errorMsg = $"Exception while disposing '{objectName}': {ex.GetType().Name} - {ex.Message}";
logAction?.Invoke(errorMsg);
System.Diagnostics.Debug.WriteLine(errorMsg);
}
}
public static async Task SafeDisposeAsync(IAsyncDisposable asyncDisposable, string objectName = "object", Action<string> logAction = null)
{
if (asyncDisposable == null)
{
return;
}
try
{
await asyncDisposable.DisposeAsync();
}
catch (Exception ex)
{
string errorMsg = $"Exception while disposing '{objectName}': {ex.GetType().Name} - {ex.Message}";
logAction?.Invoke(errorMsg);
System.Diagnostics.Debug.WriteLine(errorMsg);
}
}
public static void SafeClose(Action closeAction, string objectName = "stream", Action<string> logAction = null)
{
if (closeAction == null)
{
return;
}
try
{
closeAction();
}
catch (System.Net.Sockets.SocketException ex) when (ex.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset || ex.SocketErrorCode == System.Net.Sockets.SocketError.Shutdown)
{
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
string errorMsg = $"Exception while closing '{objectName}': {ex.GetType().Name} - {ex.Message}";
logAction?.Invoke(errorMsg);
System.Diagnostics.Debug.WriteLine(errorMsg);
}
}
}
}
+66 -110
View File
@@ -1,16 +1,11 @@
using System.Net;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Diagnostics;
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
/// <summary>
/// A lightweight HTTP server that exposes health and status information via a REST API.
/// Listens on a configurable port (use 0 for a random available port).
/// </summary>
public class HealthApiServer : IDisposable
{
private TcpListener _listener;
@@ -19,45 +14,39 @@ namespace EonaCat.Connections.Helpers
private volatile bool _running;
private readonly Func<string> _getHealthJson;
private readonly Func<string> _getStatusJson;
private int _maxRequestSize = 10 * 1024 * 1024; // 10 MB default
/// <summary>
/// Gets or sets the maximum HTTP request size in bytes.
/// Defaults to 10 MB. Set before calling Start().
/// </summary>
public int MaxRequestSize
{
get => _maxRequestSize;
set => _maxRequestSize = Math.Max(1024, value); // Minimum 1 KB
}
/// <summary>
/// Gets the actual port the server is listening on.
/// Returns 0 if the server is not started.
/// </summary>
public int Port { get; private set; }
/// <summary>
/// Gets whether the server is currently running.
/// </summary>
public bool IsRunning => _running;
/// <summary>
/// Creates a new HealthApiServer.
/// </summary>
/// <param name="getHealthJson">Callback that returns the JSON for the /health endpoint.</param>
/// <param name="getStatusJson">Callback that returns the JSON for the /status endpoint.</param>
public bool IsSharedPort { get; private set; }
internal static string GetProcessName()
{
using (var process = Process.GetCurrentProcess())
{
return process.ProcessName;
}
}
internal void StartSharedPort(int port)
{
if (_running && !IsSharedPort)
{
throw new InvalidOperationException("The health API is already using a separate listener.");
}
Port = port;
IsSharedPort = true;
_running = true;
}
public HealthApiServer(Func<string> getHealthJson, Func<string> getStatusJson)
{
_getHealthJson = getHealthJson ?? throw new ArgumentNullException(nameof(getHealthJson));
_getStatusJson = getStatusJson ?? throw new ArgumentNullException(nameof(getStatusJson));
}
/// <summary>
/// Starts the HTTP health API server.
/// </summary>
/// <param name="port">Port to listen on. Use 0 for a random available port.</param>
/// <param name="bindAddress">IP address to bind to. Use <c>IPAddress.Any</c> for Docker/container environments. Defaults to <c>IPAddress.Loopback</c>.</param>
public void Start(int port = 0, IPAddress bindAddress = null)
{
if (_running)
@@ -77,9 +66,6 @@ namespace EonaCat.Connections.Helpers
_listenTask = Task.Run(async () => await AcceptLoopAsync(token).ConfigureAwait(false), token);
}
/// <summary>
/// Stops the HTTP health API server.
/// </summary>
public void Stop()
{
if (!_running)
@@ -94,9 +80,9 @@ namespace EonaCat.Connections.Helpers
{
_listener?.Stop();
}
catch
catch (Exception)
{
// Swallow
}
try
@@ -108,6 +94,7 @@ namespace EonaCat.Connections.Helpers
}
Port = 0;
IsSharedPort = false;
}
private async Task AcceptLoopAsync(CancellationToken token)
@@ -118,7 +105,9 @@ namespace EonaCat.Connections.Helpers
try
{
client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);
_ = Task.Run(() => HandleRequestAsync(client), token);
HandlingHelpers.SafeFireAndForgetTaskAsync(
() => HandleRequestAsync(client),
"HealthApiServer.HandleRequest");
}
catch (ObjectDisposedException)
{
@@ -128,9 +117,9 @@ namespace EonaCat.Connections.Helpers
{
break;
}
catch
catch (Exception)
{
// Swallow individual connection errors to keep the loop alive
}
}
}
@@ -145,6 +134,17 @@ namespace EonaCat.Connections.Helpers
client.SendTimeout = 5000;
using var stream = client.GetStream();
await HandleRequestAsync(stream).ConfigureAwait(false);
}
}
catch (Exception)
{
}
}
internal async Task HandleRequestAsync(Stream stream, bool allowAccess = true)
{
var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false);
if (string.IsNullOrEmpty(requestLine))
@@ -162,6 +162,13 @@ namespace EonaCat.Connections.Helpers
var method = parts[0].ToUpperInvariant();
var path = parts[1].Split('?')[0].TrimEnd('/').ToLowerInvariant();
await DrainHeadersAsync(stream).ConfigureAwait(false);
if (!allowAccess)
{
await WriteResponseAsync(stream, 403, "Forbidden", "text/plain", "Forbidden").ConfigureAwait(false);
return;
}
if (method != "GET")
{
@@ -169,16 +176,22 @@ namespace EonaCat.Connections.Helpers
return;
}
// Drain remaining headers
await DrainHeadersAsync(stream).ConfigureAwait(false);
switch (path)
{
case "" or "/":
var indexJson = "{\"endpoints\":[\"/health\",\"/status\"]}";
var indexJson = "{\"endpoints\":[\"/health\",\"/status\",\"/dashboard\"]}";
await WriteResponseAsync(stream, 200, "OK", "application/json", indexJson).ConfigureAwait(false);
break;
case "/dashboard":
using (var resource = typeof(HealthApiServer).Assembly.GetManifestResourceStream("EonaCat.Connections.Helpers.TrafficDashboard.html")
?? throw new InvalidOperationException("The traffic dashboard resource is missing."))
using (var reader = new StreamReader(resource, Encoding.UTF8))
{
await WriteResponseAsync(stream, 200, "OK", "text/html", reader.ReadToEnd()).ConfigureAwait(false);
}
break;
case "/health":
var healthJson = SafeGetJson(_getHealthJson);
await WriteResponseAsync(stream, 200, "OK", "application/json", healthJson).ConfigureAwait(false);
@@ -194,12 +207,6 @@ namespace EonaCat.Connections.Helpers
break;
}
}
}
catch
{
// Swallow individual request errors
}
}
private static string SafeGetJson(Func<string> getter)
{
@@ -213,14 +220,13 @@ namespace EonaCat.Connections.Helpers
}
}
private async Task<string> ReadRequestLineAsync(NetworkStream stream)
private static async Task<string> ReadRequestLineAsync(Stream stream)
{
var sb = new StringBuilder();
var buffer = new byte[1];
var prev = (byte)0;
int maxLineSize = Math.Min(8192, _maxRequestSize); // Limit request line size
while (sb.Length < maxLineSize)
while (sb.Length < 8192)
{
int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false);
if (read == 0)
@@ -234,12 +240,6 @@ namespace EonaCat.Connections.Helpers
break;
}
// Security: Reject null bytes and other control characters that shouldn't be in HTTP headers
if (b < 32 && b != (byte)'\r' && b != (byte)'\t')
{
throw new InvalidOperationException("Invalid character in HTTP request line");
}
if (b != (byte)'\r')
{
sb.Append((char)b);
@@ -248,24 +248,16 @@ namespace EonaCat.Connections.Helpers
prev = b;
}
// Security: Check if request line exceeds limit
if (sb.Length >= maxLineSize)
{
throw new InvalidOperationException("HTTP request line exceeds maximum size");
}
return sb.ToString();
}
private async Task DrainHeadersAsync(NetworkStream stream)
private static async Task DrainHeadersAsync(Stream stream)
{
var sb = new StringBuilder();
var buffer = new byte[1];
int consecutiveNewlines = 0;
int totalBytesRead = 0;
int maxHeaderSize = Math.Min(65536, _maxRequestSize); // Limit header size to 64 KB
while (consecutiveNewlines < 2 && totalBytesRead < maxHeaderSize)
while (consecutiveNewlines < 2)
{
int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false);
if (read == 0)
@@ -273,14 +265,6 @@ namespace EonaCat.Connections.Helpers
break;
}
totalBytesRead++;
// Security: Reject null bytes in headers
if (buffer[0] == 0)
{
throw new InvalidOperationException("Null byte in HTTP headers");
}
if (buffer[0] == (byte)'\n')
{
consecutiveNewlines++;
@@ -290,43 +274,18 @@ namespace EonaCat.Connections.Helpers
consecutiveNewlines = 0;
}
}
// Security: Check if headers exceed limit
if (totalBytesRead >= maxHeaderSize)
{
throw new InvalidOperationException("HTTP headers exceed maximum size");
}
}
private async Task WriteResponseAsync(NetworkStream stream, int statusCode, string statusText, string contentType, string body)
private static async Task WriteResponseAsync(Stream stream, int statusCode, string statusText, string contentType, string body)
{
var bodyBytes = Encoding.UTF8.GetBytes(body);
// Security: Enforce maximum response size
if (bodyBytes.Length > _maxRequestSize)
{
// Send error response instead
bodyBytes = Encoding.UTF8.GetBytes("{\"error\":\"Response too large\"}");
}
// Security: Validate content type to prevent injection
if (!string.IsNullOrEmpty(contentType) &&
(contentType.Contains("\r") || contentType.Contains("\n") || contentType.Contains("\0")))
{
contentType = "application/json";
}
var header = $"HTTP/1.1 {statusCode} {statusText}\r\n" +
$"Content-Type: {contentType}; charset=utf-8\r\n" +
$"Content-Length: {bodyBytes.Length}\r\n" +
"Access-Control-Allow-Origin: *\r\n" +
"Connection: close\r\n" +
"X-Content-Type-Options: nosniff\r\n" +
"X-Frame-Options: DENY\r\n" +
"X-XSS-Protection: 1; mode=block\r\n" +
"Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n" +
"Cache-Control: no-store, no-cache, must-revalidate, private\r\n" +
"Pragma: no-cache\r\n" +
"Cache-Control: no-store\r\n" +
"\r\n";
var headerBytes = Encoding.ASCII.GetBytes(header);
@@ -335,9 +294,6 @@ namespace EonaCat.Connections.Helpers
await stream.FlushAsync().ConfigureAwait(false);
}
/// <summary>
/// Escapes a string value for safe embedding in JSON output.
/// </summary>
public static string JsonEscape(string value)
{
if (value == null)
+261
View File
@@ -0,0 +1,261 @@
using System.Collections.Concurrent;
using EonaCat.Connections.Models;
namespace EonaCat.Connections.Helpers
{
public class LoadTester : IDisposable
{
public static event EventHandler<LogMessage> OnLog;
private readonly Configuration _configuration;
private readonly int _targetConnections;
private readonly ConcurrentDictionary<string, NetworkClient> _connections;
private CancellationTokenSource _testCts;
private volatile bool _isRunning;
private DateTime _startTime;
private long _successfulConnections;
private long _failedConnections;
private long _messagesSent;
private long _bytesSent;
private long _messagesReceived;
private long _bytesReceived;
private long _errors;
public LoadTester(Configuration configuration, int targetConnections)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_targetConnections = Math.Max(1, targetConnections);
_connections = new ConcurrentDictionary<string, NetworkClient>();
}
public async Task RunAsync(TimeSpan duration, int connectionRatePerSecond = 1000, int messageRate = 1)
{
if (_isRunning)
{
throw new InvalidOperationException("Test already running");
}
_isRunning = true;
_testCts = new CancellationTokenSource(duration);
_startTime = DateTime.UtcNow;
var connectionTask = EstablishConnectionsAsync(connectionRatePerSecond, _testCts.Token);
var messageTask = SendMessagesAsync(messageRate, _testCts.Token);
var monitorTask = MonitorProgressAsync(_testCts.Token);
try
{
await Task.WhenAll(connectionTask, messageTask, monitorTask).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
finally
{
_isRunning = false;
await CloseAllConnectionsAsync();
}
}
private async Task EstablishConnectionsAsync(int connectionsPerSecond, CancellationToken token)
{
var interval = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, connectionsPerSecond));
var connectionId = 0;
try
{
while (!token.IsCancellationRequested && _connections.Count < _targetConnections)
{
var id = $"conn_{connectionId++}";
try
{
var client = new NetworkClient(_configuration);
var capturedId = id;
client.OnConnected += (sender, e) =>
{
};
client.OnGeneralError += (sender, e) =>
{
Interlocked.Increment(ref _errors);
};
client.OnSocketError += (sender, e) =>
{
Interlocked.Increment(ref _errors);
};
client.OnDisconnected += (sender, e) =>
{
_connections.TryRemove(capturedId, out _);
};
await client.ConnectAsync().ConfigureAwait(false);
if (_connections.TryAdd(id, client))
{
Interlocked.Increment(ref _successfulConnections);
}
else
{
client.Dispose();
}
}
catch
{
Interlocked.Increment(ref _failedConnections);
}
await Task.Delay(interval, token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
}
private async Task SendMessagesAsync(int messagesPerSecond, CancellationToken token)
{
var interval = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, messagesPerSecond));
var testMessage = "LOAD_TEST_MESSAGE";
try
{
while (!token.IsCancellationRequested)
{
foreach (var kvp in _connections)
{
if (token.IsCancellationRequested)
{
break;
}
try
{
await kvp.Value.SendAsync(testMessage).ConfigureAwait(false);
Interlocked.Increment(ref _messagesSent);
Interlocked.Add(ref _bytesSent, System.Text.Encoding.UTF8.GetByteCount(testMessage));
}
catch
{
Interlocked.Increment(ref _errors);
_connections.TryRemove(kvp.Key, out _);
}
}
await Task.Delay(interval, token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
}
private async Task MonitorProgressAsync(CancellationToken token)
{
try
{
while (!token.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(10), token).ConfigureAwait(false);
var elapsed = DateTime.UtcNow - _startTime;
await WriteToLogAsync($"[{elapsed:hh\\:mm\\:ss}] Connections: {_connections.Count}/{_targetConnections}, " +
$"Messages: {_messagesSent}, Bytes: {_bytesSent / (1024 * 1024)} MB, Errors: {_errors}");
}
}
catch (OperationCanceledException)
{
}
}
private async Task WriteToLogAsync(string text)
{
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = text });
}
private async Task CloseAllConnectionsAsync()
{
var tasks = _connections.Values.Select(async client =>
{
try
{
await client.DisconnectAsync().ConfigureAwait(false);
client?.Dispose();
}
catch { }
});
await Task.WhenAll(tasks).ConfigureAwait(false);
_connections.Clear();
}
public LoadTestReport GetReport()
{
var elapsed = DateTime.UtcNow - _startTime;
return new LoadTestReport
{
Duration = elapsed,
TargetConnections = _targetConnections,
ActualConnections = _connections.Count,
SuccessfulConnections = _successfulConnections,
FailedConnections = _failedConnections,
MessagesSent = _messagesSent,
BytesSent = _bytesSent,
MessagesReceived = _messagesReceived,
BytesReceived = _bytesReceived,
Errors = _errors,
MessagesPerSecond = elapsed.TotalSeconds > 0 ? _messagesSent / elapsed.TotalSeconds : 0,
MbpsSent = elapsed.TotalSeconds > 0 ? (_bytesSent * 8.0 / 1_000_000.0) / elapsed.TotalSeconds : 0,
ConnectionSuccessRate = (_successfulConnections + _failedConnections) > 0
? (100.0 * _successfulConnections) / (_successfulConnections + _failedConnections)
: 0,
};
}
public void Dispose()
{
_testCts?.Cancel();
_testCts?.Dispose();
}
}
public class LoadTestReport
{
public TimeSpan Duration { get; set; }
public int TargetConnections { get; set; }
public int ActualConnections { get; set; }
public long SuccessfulConnections { get; set; }
public long FailedConnections { get; set; }
public long MessagesSent { get; set; }
public long BytesSent { get; set; }
public long MessagesReceived { get; set; }
public long BytesReceived { get; set; }
public long Errors { get; set; }
public double MessagesPerSecond { get; set; }
public double MbpsSent { get; set; }
public double ConnectionSuccessRate { get; set; }
public override string ToString()
{
return $@"
=== Load Test Report ===
Duration: {Duration}
Connections: {ActualConnections}/{TargetConnections} (Success: {SuccessfulConnections}, Failed: {FailedConnections})
Success Rate: {ConnectionSuccessRate:F2}%
Message Rate: {MessagesPerSecond:F2} msg/sec
Throughput: {MbpsSent:F2} Mbps
Total Bytes Sent: {BytesSent / (1024 * 1024)} MB
Total Errors: {Errors}
";
}
}
}
+3 -26
View File
@@ -1,13 +1,10 @@
using System.Collections.Concurrent;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Text;
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class NetworkMonitor : IDisposable
{
private readonly string _targetHost;
@@ -29,9 +26,6 @@ namespace EonaCat.Connections.Helpers
public bool IsRunning => _isRunning;
public string TargetHost => _targetHost;
/// <summary>
/// Gets whether automatic HTML report generation is currently running.
/// </summary>
public bool IsAutoHtmlReportRunning => _autoReportRunning;
public NetworkMonitor(string targetHost = "127.0.0.1", int pingIntervalMs = 5000, int maxHistory = 1000)
@@ -177,7 +171,7 @@ namespace EonaCat.Connections.Helpers
}
catch
{
// Network interface stats may not be available on all platforms
}
return sample;
@@ -266,7 +260,6 @@ namespace EonaCat.Connections.Helpers
report.MinLatencyMs = minRtt;
report.MaxLatencyMs = maxRtt;
// Calculate jitter (standard deviation of latency)
double sumSquaredDiff = 0;
foreach (var s in reachable)
{
@@ -277,7 +270,6 @@ namespace EonaCat.Connections.Helpers
report.JitterMs = Math.Sqrt(sumSquaredDiff / reachable.Count);
}
// Detect outage windows
bool inOutage = false;
DateTime outageStart = DateTime.MinValue;
@@ -311,7 +303,6 @@ namespace EonaCat.Connections.Helpers
});
}
// Bandwidth estimate between last two samples
if (samples.Length >= 2)
{
var prev = samples[samples.Length - 2];
@@ -340,12 +331,6 @@ namespace EonaCat.Connections.Helpers
_autoReportCts?.Dispose();
}
/// <summary>
/// Starts periodic automatic generation of the network health HTML report.
/// </summary>
/// <param name="outputDirectory">Directory where the HTML file is written.</param>
/// <param name="intervalSeconds">Interval in seconds between report generations.</param>
/// <param name="fileName">The HTML file name.</param>
public void StartAutoHtmlReport(string outputDirectory, int intervalSeconds = 60, string fileName = "status-network.html")
{
if (_autoReportRunning)
@@ -378,7 +363,7 @@ namespace EonaCat.Connections.Helpers
}
catch
{
// Swallow to keep the loop alive
}
try
@@ -393,9 +378,6 @@ namespace EonaCat.Connections.Helpers
}, token);
}
/// <summary>
/// Stops the automatic HTML report generation.
/// </summary>
public void StopAutoHtmlReport()
{
if (!_autoReportRunning)
@@ -530,7 +512,6 @@ namespace EonaCat.Connections.Helpers
sb.AppendLine("<div class=\"container\">");
sb.AppendLine($"<h1>{HtmlEncode(title)}</h1>");
// Status banner
if (TotalSamples > 0)
{
var bannerClass = IsStable ? "status-stable" : "status-unstable";
@@ -538,7 +519,6 @@ namespace EonaCat.Connections.Helpers
sb.AppendLine($"<div class=\"status-banner {bannerClass}\">{bannerText}</div>");
}
// Summary cards
var uptimeClass = UptimePercentage >= 99 ? "ok" : UptimePercentage >= 95 ? "warn" : "error";
var latencyClass = AverageLatencyMs < 50 ? "ok" : AverageLatencyMs < 150 ? "warn" : "error";
var jitterClass = JitterMs < 20 ? "ok" : JitterMs < 50 ? "warn" : "error";
@@ -552,13 +532,11 @@ namespace EonaCat.Connections.Helpers
sb.AppendLine($"<div class=\"card {(FailedPings > 0 ? "error" : "ok")}\"><div class=\"label\">Failed Pings</div><div class=\"value\">{FailedPings}</div></div>");
sb.AppendLine("</div>");
// Uptime progress bar
sb.AppendLine("<h2>Uptime</h2>");
var barColor = UptimePercentage >= 99 ? "#27ae60" : UptimePercentage >= 95 ? "#f39c12" : "#e74c3c";
var barWidth = Math.Max(0, Math.Min(100, UptimePercentage));
sb.AppendLine($"<div class=\"progress-bg\"><div class=\"progress-bar\" style=\"width:{barWidth:F1}%;background:{barColor}\">{UptimePercentage:F2}%</div></div>");
// Latency / Bandwidth
sb.AppendLine("<h2>Performance</h2>");
sb.AppendLine("<div class=\"summary-cards\">");
sb.AppendLine($"<div class=\"card\"><div class=\"label\">Min Latency</div><div class=\"value\">{MinLatencyMs} ms</div></div>");
@@ -567,7 +545,6 @@ namespace EonaCat.Connections.Helpers
sb.AppendLine($"<div class=\"card\"><div class=\"label\">Send Bandwidth</div><div class=\"value\" style=\"font-size:1em\">{FormatBytes(CurrentSendBytesPerSecond)}/s</div></div>");
sb.AppendLine("</div>");
// Outage windows
sb.AppendLine("<h2>Outage History</h2>");
if (OutageWindows.Count == 0)
{
@@ -0,0 +1,97 @@
using System.Text;
namespace EonaCat.Connections.Helpers
{
internal sealed class ProtocolProbeStream : Stream
{
private readonly Stream _inner;
private readonly MemoryStream _prefix = new MemoryStream();
private readonly byte[] _probeBuffer = new byte[8192];
private Task<int>? _pendingRead;
internal ProtocolProbeStream(Stream inner)
{
_inner = inner;
}
internal async Task<bool> IsHttpAsync(CancellationToken token)
{
var prefixes = new[] { "GET /", "HEAD /", "POST /", "PUT /", "DELETE /", "OPTIONS /", "PATCH /" };
try
{
while (_prefix.Length < 9)
{
_pendingRead = _inner.ReadAsync(_probeBuffer, 0, _probeBuffer.Length, token);
if (await Task.WhenAny(_pendingRead, Task.Delay(250, token)).ConfigureAwait(false) != _pendingRead)
{
token.ThrowIfCancellationRequested();
_ = _pendingRead.ContinueWith(task => { _ = task.Exception; }, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
return false;
}
var count = await _pendingRead.ConfigureAwait(false);
_pendingRead = null;
if (count == 0) return false;
_prefix.Write(_probeBuffer, 0, count);
var text = Encoding.ASCII.GetString(_prefix.GetBuffer(), 0, (int)Math.Min(_prefix.Length, 9));
if (prefixes.Any(prefix => text.StartsWith(prefix, StringComparison.Ordinal))) return true;
if (!prefixes.Any(prefix => prefix.StartsWith(text, StringComparison.Ordinal))) return false;
}
return false;
}
finally
{
_prefix.Position = 0;
}
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || count < 0 || offset > buffer.Length - count) throw new ArgumentOutOfRangeException();
cancellationToken.ThrowIfCancellationRequested();
if (count == 0) return 0;
if (_prefix.Position < _prefix.Length) return _prefix.Read(buffer, offset, count);
if (_pendingRead != null)
{
var pending = _pendingRead;
var received = await pending.ConfigureAwait(false);
_pendingRead = null;
if (received == 0) return 0;
var position = _prefix.Length;
_prefix.Position = position;
_prefix.Write(_probeBuffer, 0, received);
_prefix.Position = position;
return _prefix.Read(buffer, offset, count);
}
return await _inner.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
public override void Write(byte[] buffer, int offset, int count) => _inner.Write(buffer, offset, count);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _inner.WriteAsync(buffer, offset, count, cancellationToken);
public override void Flush() => _inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => _inner.FlushAsync(cancellationToken);
public override bool CanRead => _inner.CanRead;
public override bool CanWrite => _inner.CanWrite;
public override bool CanSeek => false;
public override bool CanTimeout => _inner.CanTimeout;
public override int ReadTimeout { get => _inner.ReadTimeout; set => _inner.ReadTimeout = value; }
public override int WriteTimeout { get => _inner.WriteTimeout; set => _inner.WriteTimeout = value; }
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
_inner.Dispose();
_prefix.Dispose();
}
base.Dispose(disposing);
}
}
}
@@ -1,253 +0,0 @@
using System;
using System.Collections.Concurrent;
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
/// <summary>
/// Provides security validation utilities to protect against common network attacks
/// including buffer overflows, memory exhaustion (decompression bombs), malformed packets,
/// and injection attacks.
/// </summary>
public static class SecurityValidator
{
private static readonly ConcurrentDictionary<string, RateLimitEntry> _rateLimitCache =
new ConcurrentDictionary<string, RateLimitEntry>();
private class RateLimitEntry
{
public long RequestCount;
public DateTime WindowStart;
}
/// <summary>
/// Validates a length prefix value against configuration limits.
/// Prevents buffer overflow and memory exhaustion attacks by:
/// - Rejecting negative or zero lengths
/// - Rejecting lengths exceeding configured maximum
/// - Rejecting obviously malformed values (e.g., impossibly large lengths)
/// </summary>
public static bool ValidateLengthPrefix(long messageLengthValue, int maxMessageSize)
{
// Reject negative, zero, or non-positive values
if (messageLengthValue <= 0)
{
return false;
}
// Reject values exceeding maximum allowed message size
if (messageLengthValue > maxMessageSize)
{
return false;
}
// Reject impossibly large values that could indicate malformed data
if (messageLengthValue > int.MaxValue)
{
return false;
}
return true;
}
/// <summary>
/// Validates message stream size to prevent memory exhaustion attacks.
/// Checks if accumulated message data exceeds configured thresholds.
/// </summary>
public static bool ValidateMessageStreamSize(long currentStreamLength, long maxStreamSize)
{
if (currentStreamLength <= 0 || maxStreamSize <= 0)
{
return true; // No limit configured
}
return currentStreamLength < maxStreamSize;
}
/// <summary>
/// Validates UDP packet size to prevent buffer overflow attacks.
/// </summary>
public static bool ValidateUdpPacketSize(int receivedBytes, int bufferSize)
{
// UDP packet should not exceed buffer size
if (receivedBytes <= 0 || receivedBytes > bufferSize)
{
return false;
}
return true;
}
/// <summary>
/// Implements basic rate limiting per source IP address.
/// Returns true if request is within rate limit, false if limit exceeded.
/// </summary>
public static bool CheckRateLimit(string sourceAddress, int maxRequestsPerSecond, int windowSizeSeconds = 1)
{
if (string.IsNullOrEmpty(sourceAddress) || maxRequestsPerSecond <= 0)
{
return true; // No rate limit configured
}
var now = DateTime.UtcNow;
var entry = _rateLimitCache.AddOrUpdate(sourceAddress,
new RateLimitEntry { RequestCount = 1, WindowStart = now },
(key, existing) =>
{
// Check if we're still in the same window
var timeDiff = now - existing.WindowStart;
if (timeDiff.TotalSeconds < windowSizeSeconds)
{
existing.RequestCount++;
}
else
{
// Reset window
existing.RequestCount = 1;
existing.WindowStart = now;
}
return existing;
});
return entry.RequestCount <= maxRequestsPerSecond;
}
/// <summary>
/// Validates HTTP header names and values to prevent header injection attacks.
/// </summary>
public static bool ValidateHttpHeader(string headerName, string headerValue)
{
if (string.IsNullOrEmpty(headerName) || string.IsNullOrEmpty(headerValue))
{
return false;
}
// Check for newline characters that could be used in HTTP header injection
if (headerName.Contains("\r") || headerName.Contains("\n") ||
headerValue.Contains("\r") || headerValue.Contains("\n"))
{
return false;
}
// Check for null bytes
if (headerName.Contains("\0") || headerValue.Contains("\0"))
{
return false;
}
return true;
}
/// <summary>
/// Validates that a message doesn't contain null bytes which could be used for injection attacks.
/// </summary>
public static bool ValidateMessageContent(byte[] data)
{
if (data == null || data.Length == 0)
{
return true; // Empty is generally OK
}
// This is optional depending on your protocol - some protocols may legitimately use null bytes
// For now, we'll allow them but this can be made stricter if needed
return true;
}
/// <summary>
/// Validates delimiter to prevent delimiter injection attacks.
/// </summary>
public static bool ValidateDelimiter(byte[] delimiter)
{
if (delimiter == null || delimiter.Length == 0)
{
return false;
}
// Delimiter should be reasonably small
if (delimiter.Length > 256)
{
return false;
}
return true;
}
/// <summary>
/// Detects potential decompression bomb by checking if uncompressed size ratio is too high.
/// </summary>
public static bool ValidateCompressionRatio(long compressedSize, long decompressedSize, double maxRatio = 100.0)
{
if (compressedSize <= 0 || decompressedSize <= 0)
{
return true; // Can't validate
}
double ratio = (double)decompressedSize / compressedSize;
return ratio <= maxRatio;
}
/// <summary>
/// Cleans up old rate limit entries to prevent memory leaks.
/// Should be called periodically from cleanup/maintenance tasks.
/// </summary>
public static void CleanupRateLimitCache(int maxAgeSeconds = 300)
{
var now = DateTime.UtcNow;
var keysToRemove = new System.Collections.Generic.List<string>();
foreach (var kvp in _rateLimitCache)
{
var age = now - kvp.Value.WindowStart;
if (age.TotalSeconds > maxAgeSeconds)
{
keysToRemove.Add(kvp.Key);
}
}
foreach (var key in keysToRemove)
{
_rateLimitCache.TryRemove(key, out _);
}
}
/// <summary>
/// Sanitizes error messages to prevent information leakage.
/// </summary>
public static string SanitizeErrorMessage(string message, bool isInternal = false)
{
if (string.IsNullOrEmpty(message))
{
return "An error occurred";
}
if (isInternal)
{
// Internal logs can include full details
return message;
}
// External error messages should be generic to avoid info leakage
// Only include safe error information back to clients
if (message.Contains("socket", StringComparison.OrdinalIgnoreCase) ||
message.Contains("connection", StringComparison.OrdinalIgnoreCase))
{
return "Connection error occurred";
}
if (message.Contains("timeout", StringComparison.OrdinalIgnoreCase))
{
return "Operation timed out";
}
if (message.Contains("invalid", StringComparison.OrdinalIgnoreCase) ||
message.Contains("malformed", StringComparison.OrdinalIgnoreCase))
{
return "Invalid data received";
}
return "An error occurred";
}
}
}
@@ -1,29 +1,17 @@
using System;
using System.Diagnostics;
using System.Diagnostics;
using System.Net.Security;
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
/// <summary>
/// Helper class for tracking and diagnosing SSL/TLS handshake performance and errors.
/// </summary>
public class SslHandshakeDiagnostics
{
private readonly SslMetrics _metrics = new();
private readonly Stopwatch _totalStopwatch = new();
private Stopwatch? _stageStopwatch;
/// <summary>
/// Gets the current metrics object.
/// </summary>
public SslMetrics Metrics => _metrics;
/// <summary>
/// Starts tracking a new SSL handshake attempt.
/// </summary>
public void StartHandshake(string remoteEndPoint, bool mutualAuthRequired)
{
_totalStopwatch.Restart();
@@ -35,17 +23,11 @@ namespace EonaCat.Connections.Helpers
_metrics.FailureReason = null;
}
/// <summary>
/// Marks the start of a specific SSL stage (e.g., AuthenticateAsServer).
/// </summary>
public void StartStage(string stageName)
{
_stageStopwatch = Stopwatch.StartNew();
}
/// <summary>
/// Marks the end of a specific SSL stage and records the duration.
/// </summary>
public void EndStage(string stageName)
{
if (_stageStopwatch == null)
@@ -82,9 +64,6 @@ namespace EonaCat.Connections.Helpers
_stageStopwatch = null;
}
/// <summary>
/// Records successful SSL handshake completion and captures protocol details.
/// </summary>
public void RecordSuccess(SslStream sslStream)
{
_totalStopwatch.Stop();
@@ -103,16 +82,13 @@ namespace EonaCat.Connections.Helpers
}
catch
{
// No cross-platform way to get these details, so ignore if not available.
}
}
_metrics.CumulativeDuration = _totalStopwatch.Elapsed;
}
/// <summary>
/// Records SSL handshake failure with error details.
/// </summary>
public void RecordFailure(Exception exception, bool isRecoverable)
{
_totalStopwatch.Stop();
@@ -123,11 +99,6 @@ namespace EonaCat.Connections.Helpers
_metrics.CumulativeDuration = _totalStopwatch.Elapsed;
}
/// <summary>
/// Analyzes the failure and determines if it's recoverable.
/// Non-recoverable failures: authentication failures, certificate errors, protocol mismatches
/// Recoverable failures: timeouts, network interruptions, EOF during handshake
/// </summary>
public static bool IsRecoverableFailure(Exception exception)
{
if (exception == null)
@@ -138,7 +109,6 @@ namespace EonaCat.Connections.Helpers
var message = exception.Message?.ToLower() ?? "";
var typeName = exception.GetType().Name.ToLower();
// Non-recoverable SSL authentication and certificate errors
if (typeName.Contains("authenticationexception"))
{
return false;
@@ -174,7 +144,6 @@ namespace EonaCat.Connections.Helpers
return false;
}
// Check for handshake_failure TLS alerts
if (message.Contains("handshake_failure"))
{
return false;
@@ -190,7 +159,6 @@ namespace EonaCat.Connections.Helpers
return false;
}
// Recoverable I/O and network errors
if (message.Contains("0 bytes from the transport stream"))
{
return true;
@@ -251,13 +219,9 @@ namespace EonaCat.Connections.Helpers
return IsRecoverableFailure(exception.InnerException);
}
// Default: assume recoverable for network-layer exceptions
return typeName.Contains("exception");
}
/// <summary>
/// Returns a diagnostic summary of the handshake attempt.
/// </summary>
public override string ToString() => _metrics.ToString();
}
}
+2 -62
View File
@@ -1,103 +1,43 @@
using System;
namespace EonaCat.Connections.Helpers
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
/// <summary>
/// Tracks metrics and timing information for SSL/TLS handshake stages.
/// </summary>
public class SslMetrics
{
/// <summary>
/// Gets the timestamp when the SSL handshake attempt started.
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// Gets the timestamp when the SSL handshake completed (success or final failure).
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// Gets the total duration of the SSL handshake attempt.
/// </summary>
public TimeSpan? TotalDuration => EndTime.HasValue ? EndTime.Value - StartTime : null;
/// <summary>
/// Gets the duration of the AuthenticateAsServer call (server-side).
/// </summary>
public TimeSpan? ServerAuthenticationDuration { get; set; }
/// <summary>
/// Gets the duration of the AuthenticateAsClient call (client-side).
/// </summary>
public TimeSpan? ClientAuthenticationDuration { get; set; }
/// <summary>
/// Gets the time spent retrying SSL handshakes after failures.
/// </summary>
public TimeSpan? RetryDelayDuration { get; set; }
/// <summary>
/// Gets the total time spent in all SSL handshake attempts including retries.
/// </summary>
public TimeSpan? CumulativeDuration { get; set; }
/// <summary>
/// Gets the number of SSL handshake attempts made.
/// </summary>
public int AttemptCount { get; set; }
/// <summary>
/// Gets the SSL protocol version negotiated (e.g., "Tls13", "Tls12").
/// </summary>
public string? SslProtocolVersion { get; set; }
/// <summary>
/// Gets the cipher algorithm used (e.g., "Aes256", "ChaCha20").
/// </summary>
public string? CipherAlgorithm { get; set; }
/// <summary>
/// Gets the hash algorithm used (e.g., "Sha256").
/// </summary>
public string? HashAlgorithm { get; set; }
/// <summary>
/// Gets the key exchange algorithm used (e.g., "Ecdh").
/// </summary>
public string? KeyExchangeAlgorithm { get; set; }
/// <summary>
/// Gets whether the SSL handshake was successful.
/// </summary>
public bool IsSuccessful { get; set; }
/// <summary>
/// Gets the exception message if the handshake failed.
/// </summary>
public string? FailureReason { get; set; }
/// <summary>
/// Gets whether the failure is recoverable (can retry) or not.
/// </summary>
public bool IsRecoverableFailure { get; set; }
/// <summary>
/// Gets the remote endpoint that was connected to/from.
/// </summary>
public string? RemoteEndPoint { get; set; }
/// <summary>
/// Gets whether mutual authentication (client certificate) was required.
/// </summary>
public bool MutualAuthenticationRequired { get; set; }
/// <summary>
/// Returns a formatted string summary of the SSL handshake metrics.
/// </summary>
public override string ToString()
{
var result = $"SSL Metrics: Attempt {AttemptCount}, ";
+75 -13
View File
@@ -1,23 +1,85 @@
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
internal static class StringHelper
namespace EonaCat.Connections.Helpers
{
public class StringHelper
{
public static string GetTextBetweenTags(this string value,
string startTag,
string endTag)
public static event EventHandler<string> OnLog;
public static string GetTextBetweenTags(string message, string startTag, string endTag)
{
if (value.Contains(startTag) && value.Contains(endTag))
int startIndex = message.IndexOf(startTag);
if (startIndex == -1)
{
int index = value.IndexOf(startTag) + startTag.Length;
return value.Substring(index, value.IndexOf(endTag) - index);
OnLog?.Invoke(null, $"Start tag not found in the message. => {message}");
return string.Empty;
}
else
int endIndex = message.IndexOf(endTag, startIndex + startTag.Length);
if (endIndex == -1)
{
return null;
OnLog?.Invoke(null, $"End tag not found in the message. => {message}");
return string.Empty;
}
int length = endIndex - startIndex - startTag.Length;
if (length < 0)
{
OnLog?.Invoke(null, $"End tag appears before the start tag. => {message}");
return string.Empty;
}
return message.Substring(startIndex + startTag.Length, length);
}
public static string? SanitizeUsername(string username, bool removeDomain = true)
{
if (string.IsNullOrWhiteSpace(username))
{
return username;
}
if (removeDomain && username.Contains("\\"))
{
var parts = username.Split('\\');
if (parts.Length == 2)
{
return parts[1];
}
}
// Remove the dollar sign and anything after it (for service accounts)
if (username.Contains("$"))
{
var index = username.IndexOf("$");
if (index > 0)
{
return username.Substring(0, index);
}
}
return username;
}
public static string SanitizeComputerName(string machineName)
{
if (string.IsNullOrWhiteSpace(machineName))
{
return machineName;
}
// Remove the dollar sign and anything after it (for service accounts)
if (machineName.Contains("$"))
{
var index = machineName.IndexOf("$");
if (index > 0)
{
return machineName.Substring(0, index);
}
}
return machineName;
}
}
}
@@ -2,9 +2,6 @@
namespace EonaCat.Connections.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public static class TcpSeparators
{
public static byte[] NewLine => Encoding.UTF8.GetBytes("\n");
@@ -0,0 +1,196 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>EonaCat.Connections | Traffic</title>
<style>
:root{--ink:#252c30;--muted:#626d72;--line:#d5dddf;--in:#007f78;--out:#c44835;--paper:#f4f7f6}
*{box-sizing:border-box;letter-spacing:0}body{margin:0;background:var(--paper);color:var(--ink);font:15px 'Segoe UI',sans-serif}main{max-width:1440px;margin:auto;padding:28px}header,.toolbar,.legend{display:flex;align-items:center;gap:16px;flex-wrap:wrap}header{justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:22px}h1{font-size:26px;margin:0;font-weight:650}h2{font-size:18px;margin:0}p{margin:7px 0;color:var(--muted)}button,select{font:inherit;background:white;border:1px solid #aebcbd;border-radius:4px;padding:8px;min-height:38px;color:var(--ink)}button{cursor:pointer;min-width:40px}button:hover{background:#e5efec}button:focus-visible,select:focus-visible{outline:2px solid var(--in);outline-offset:3px}.toolbar{margin:22px 0;justify-content:space-between}.controls{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.state{display:flex;align-items:center;gap:8px;color:var(--muted)}.dot{width:9px;height:9px;background:var(--in);border-radius:50%}.state[data-state=error] .dot{background:var(--out)}.state[data-state=paused] .dot{background:#b07916}.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));border-top:1px solid var(--line);border-bottom:1px solid var(--line)}.metric{padding:20px 16px;border-right:1px solid var(--line);min-width:0}.metric:last-child{border:0}.label{font-size:12px;text-transform:uppercase;color:var(--muted);margin-bottom:10px}.value{font-size:27px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.sub{color:var(--muted);font-size:13px;margin-top:8px}.incoming{color:var(--in)}.outgoing{color:var(--out)}.charts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:28px;margin-top:28px}.chart-head{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.legend{gap:12px;font-size:12px;color:var(--muted)}.legend span:before{content:'';display:inline-block;width:15px;height:3px;margin:0 6px 3px 0;background:var(--in)}.legend .sent:before{background:var(--out)}.plot{height:250px;position:relative;margin-top:12px}canvas{display:block;width:100%;height:100%}.clients{margin-top:30px;border-top:1px solid var(--line);padding-top:22px}.table-wrap{overflow:auto;margin-top:16px}table{width:100%;border-collapse:collapse;text-align:left;background:white}th,td{padding:12px;border-bottom:1px solid var(--line);font-size:13px;overflow-wrap:anywhere}th{font-weight:600;color:var(--muted)}.empty{text-align:center;color:var(--muted)}footer{margin-top:24px;color:var(--muted);font-size:12px}#endpoint{overflow-wrap:anywhere}#notice{min-height:20px;color:var(--out);font-size:13px;margin-top:12px}
@media(max-width:760px){main{padding:18px}.metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.metric:nth-child(2){border-right:0}.metric:nth-child(-n+2){border-bottom:1px solid var(--line)}.charts{grid-template-columns:1fr}h1{font-size:22px}.value{font-size:23px}.plot{height:220px}}
</style>
<style>.server-metrics{grid-template-columns:repeat(4,minmax(0,1fr));margin-top:0;border-top:0}.server-metrics[hidden]{display:none}@media(max-width:760px){.server-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.server-metrics .metric:nth-child(2){border-right:0}.server-metrics .metric:nth-child(-n+2){border-bottom:1px solid var(--line)}}</style>
</head>
<body>
<main>
<header><div><h1 id="appName">EonaCat.Connections</h1><p id="endpoint">Traffic Monitor</p></div><div class="state" id="state" role="status"><span class="dot"></span><span id="status">Connecting</span></div></header>
<div class="toolbar"><h2>Traffic Overview</h2><div class="controls"><label for="window">Window</label><select id="window"><option value="60">1 minute</option><option value="300" selected>5 minutes</option><option value="900">15 minutes</option></select><button id="pause" title="Pause sampling" aria-label="Pause sampling">&#10074;&#10074;</button><button id="export" title="Download traffic CSV" aria-label="Download traffic CSV">&#8595;</button></div></div>
<section class="metrics" aria-label="Traffic statistics">
<div class="metric"><div class="label">Incoming</div><div class="value incoming" id="receiveRate">--</div><div class="sub" id="receiveTotal">-- received</div></div>
<div class="metric"><div class="label">Outgoing</div><div class="value outgoing" id="sendRate">--</div><div class="sub" id="sendTotal">-- sent</div><div class="sub" id="lastSent">Last sent (local): --</div></div>
<div class="metric"><div class="label">Messages / second</div><div class="value" id="messageRate">--</div><div class="sub" id="messageTotal">-- messages</div></div>
<div class="metric"><div class="label" id="connectionLabel">Connections</div><div class="value" id="connections">--</div><div class="sub" id="uptime">-- uptime</div></div>
</section>
<section class="metrics server-metrics" id="serverStats" aria-label="Connection statistics" hidden>
<div class="metric"><div class="label">Total Connections</div><div class="value" id="totalConnections">--</div></div>
<div class="metric"><div class="label">Dropped Connections</div><div class="value" id="droppedConnections">--</div></div>
<div class="metric"><div class="label">Dropped Packets</div><div class="value" id="droppedPackets">--</div></div>
<div class="metric"><div class="label">Capacity</div><div class="value" id="capacity">--</div><div class="sub" id="capacityUsage">-- utilization</div></div>
<div class="metric"><div class="label">Transport Security</div><div class="value" id="transportSecurity">--</div><div class="sub" id="serverProtocol">-- protocol</div></div>
<div class="metric"><div class="label">SSL Errors</div><div class="value" id="sslErrors">--</div></div>
<div class="metric"><div class="label">Started</div><div class="value" id="startedAt">--</div></div>
</section>
<div id="notice" role="status"></div>
<section class="charts" aria-label="Traffic history">
<div><div class="chart-head"><h2>Bandwidth</h2><div class="legend"><span>Received</span><span class="sent">Sent</span></div></div><div class="plot"><canvas id="bandwidth" role="img" aria-label="Incoming and outgoing bytes per second over time"></canvas></div></div>
<div><div class="chart-head"><h2>Message Rate</h2><div class="legend"><span>Received</span><span class="sent">Sent</span></div></div><div class="plot"><canvas id="messages" role="img" aria-label="Incoming and outgoing messages per second over time"></canvas></div></div>
</section>
<section class="clients" id="clientSection" hidden><h2>Connected Clients</h2><div class="table-wrap"><table><thead><tr><th>Client</th><th>Endpoint</th><th>Connected</th><th>Idle</th><th>Received</th><th>Last Received (local)</th><th>Sent</th><th>Last Sent (local)</th><th>Security</th></tr></thead><tbody id="clients"></tbody></table></div></section>
<footer id="updated">Waiting for traffic samples</footer>
</main>
<script>
'use strict';
const samples = [];
let previous = null;
let paused = false;
let samplingVersion = 0;
const element = id => document.getElementById(id);
function bytes(value) {
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
let unit = 0;
while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
return value.toLocaleString(undefined, {maximumFractionDigits: unit ? 2 : 0}) + ' ' + units[unit];
}
function rates(before, after, seconds) {
const keys = ['bytesReceived', 'bytesSent', 'messagesReceived', 'messagesSent'];
const reset = keys.some(key => after[key] < before[key]);
return keys.map(key => reset || seconds <= 0 ? 0 : (after[key] - before[key]) / seconds);
}
function setState(text, state) { element('status').textContent = text; element('state').dataset.state = state; }
function localTime(value) { return value ? new Date(value).toLocaleString() : 'No data sent'; }
function duration(seconds) {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
return (days ? days + 'd ' : '') + hours + 'h ' + minutes + 'm';
}
function draw(id, offset, format) {
const canvas = element(id);
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const ratio = window.devicePixelRatio || 1;
canvas.width = Math.round(width * ratio); canvas.height = Math.round(height * ratio);
const context = canvas.getContext('2d');
context.scale(ratio, ratio);
const now = samples.length ? samples[samples.length - 1].time : Date.now();
const duration = Number(element('window').value) * 1000;
const visible = samples.filter(sample => sample.time >= now - duration);
const left = 78, top = 14, right = width - 12, bottom = height - 30;
const maximum = Math.max(1, ...visible.map(sample => Math.max(sample.values[offset], sample.values[offset + 1]))) * 1.15;
context.font = "11px 'Segoe UI', sans-serif";
context.lineWidth = 1;
for (let tick = 0; tick <= 4; tick++) {
const vertical = bottom - (bottom - top) * tick / 4;
context.strokeStyle = '#d5dddf'; context.beginPath(); context.moveTo(left, vertical); context.lineTo(right, vertical); context.stroke();
context.fillStyle = '#626d72'; context.textAlign = 'right'; context.fillText(format(maximum * tick / 4), left - 8, vertical + 4);
}
for (let series = 0; series < 2; series++) {
context.strokeStyle = series ? '#c44835' : '#007f78'; context.lineWidth = 2;
context.beginPath();
visible.forEach((sample, index) => {
const horizontal = left + (sample.time - now + duration) / duration * (right - left);
const vertical = bottom - sample.values[offset + series] / maximum * (bottom - top);
if (!index || sample.gap) context.moveTo(horizontal, vertical); else context.lineTo(horizontal, vertical);
});
context.stroke();
}
context.fillStyle = '#626d72'; context.textAlign = 'left'; context.fillText(new Date(now - duration).toLocaleTimeString(), left, height - 8);
context.textAlign = 'right'; context.fillText(new Date(now).toLocaleTimeString(), right, height - 8);
if (visible.length < 2) { context.textAlign = 'center'; context.fillText('Waiting for samples', (left + right) / 2, height / 2); }
}
function redraw() { draw('bandwidth', 0, value => bytes(value) + '/s'); draw('messages', 2, value => value.toLocaleString(undefined, {maximumFractionDigits: 1}) + '/s'); }
function render(status, sample) {
const processName = status.processName || 'EonaCat.Connections';
element('appName').textContent = processName;
document.title = processName + ' | Traffic';
element('endpoint').textContent = (status.type === 'server' ? 'Server' : 'Client') + ' / ' + (status.listenAddress || status.serverAddress || '') + ' / ' + status.protocol;
element('receiveRate').textContent = sample ? bytes(sample.values[0]) + '/s' : '--';
element('sendRate').textContent = sample ? bytes(sample.values[1]) + '/s' : '--';
element('receiveTotal').textContent = bytes(status.bytesReceived) + ' received';
element('sendTotal').textContent = bytes(status.bytesSent) + ' sent';
element('lastSent').textContent = 'Last sent (local): ' + localTime(status.lastDataSentUtc);
element('messageRate').textContent = sample ? (sample.values[2] + sample.values[3]).toFixed(1) : '--';
element('messageTotal').textContent = status.messagesReceived.toLocaleString() + ' in / ' + status.messagesSent.toLocaleString() + ' out';
element('connectionLabel').textContent = status.type === 'server' ? 'Connections' : 'Connection';
element('connections').textContent = status.type === 'server' ? status.activeConnections : status.isConnected ? 'Connected' : 'Disconnected';
element('uptime').textContent = Math.floor(status.uptimeSeconds / 3600) + 'h ' + Math.floor(status.uptimeSeconds % 3600 / 60) + 'm uptime';
element('serverStats').hidden = status.type !== 'server';
if (status.type === 'server') {
element('totalConnections').textContent = status.totalConnections.toLocaleString();
element('droppedConnections').textContent = status.droppedConnections.toLocaleString();
element('droppedPackets').textContent = status.droppedPackets.toLocaleString();
const maximum = Number(status.maxConnections);
element('capacity').textContent = maximum > 0 ? status.activeConnections.toLocaleString() + ' / ' + maximum.toLocaleString() : status.activeConnections.toLocaleString() + ' / Unlimited';
element('capacityUsage').textContent = maximum > 0 ? (status.activeConnections / maximum * 100).toFixed(1) + '% utilized' : 'No connection limit';
element('transportSecurity').textContent = status.isEncrypted ? 'AES' : status.isSecure ? 'TLS' : 'Plain';
element('serverProtocol').textContent = status.protocol + ' protocol';
element('sslErrors').textContent = (status.sslErrors?.total ?? 0).toLocaleString();
element('startedAt').textContent = status.startTimeUtc ? new Date(status.startTimeUtc).toLocaleString() : '--';
}
element('clientSection').hidden = status.type !== 'server';
const rows = element('clients'); rows.replaceChildren();
for (const client of status.clients || []) {
const row = document.createElement('tr');
for (const value of [client.nickname || client.id, client.remoteEndPoint, duration(client.connectedTimeSeconds), duration(client.idleTimeSeconds), bytes(client.bytesReceived), localTime(client.lastDataReceivedUtc), bytes(client.bytesSent), localTime(client.lastDataSentUtc), client.isEncrypted ? 'AES' : client.isSecure ? 'TLS' : 'Plain']) {
const cell = document.createElement('td'); cell.textContent = value || '-'; row.appendChild(cell);
}
rows.appendChild(row);
}
if (!rows.children.length) { const row = rows.insertRow(); const cell = row.insertCell(); cell.colSpan = 9; cell.className = 'empty'; cell.textContent = 'No clients connected'; }
element('updated').textContent = 'Updated ' + new Date().toLocaleTimeString() + ' / ' + samples.length + ' samples';
redraw();
}
async function poll() {
const version = samplingVersion;
try {
if (paused) return;
try {
const response = await fetch('/status', {cache: 'no-store', signal: AbortSignal.timeout(5000)});
if (!response.ok) throw new Error('Status unavailable (HTTP ' + response.status + ')');
const status = await response.json();
if (paused || version !== samplingVersion) return;
if (status.error) throw new Error(status.error);
for (const key of ['bytesReceived', 'bytesSent', 'messagesReceived', 'messagesSent', 'uptimeSeconds']) {
if (!Number.isFinite(status[key]) || status[key] < 0) throw new Error('Invalid traffic counters');
}
const time = Date.now(), monotonic = performance.now();
let sample = null;
if (previous) {
const seconds = (monotonic - previous.monotonic) / 1000;
sample = {time, values: rates(previous.status, status, seconds), gap: seconds > 5 || (samples.length > 0 && time - samples[samples.length - 1].time > 5000)};
samples.push(sample);
while (samples.length > 900 || (samples.length && samples[0].time < time - 900000)) samples.shift();
}
previous = {status, monotonic};
render(status, sample); element('notice').textContent = '';
setState('Live', 'live');
} catch (error) {
if (paused || version !== samplingVersion) return;
previous = null;
setState('Unavailable', 'error');
element('notice').textContent = error.message + '. Retrying...';
element('receiveRate').textContent = '--'; element('sendRate').textContent = '--'; element('messageRate').textContent = '--';
}
} finally {
setTimeout(poll, 1000);
}
}
element('pause').addEventListener('click', () => {
paused = !paused; previous = null; samplingVersion++;
element('pause').innerHTML = paused ? '&#9654;' : '&#10074;&#10074;';
const label = paused ? 'Resume sampling' : 'Pause sampling';
element('pause').title = label; element('pause').setAttribute('aria-label', label);
setState(paused ? 'Paused' : 'Connecting', paused ? 'paused' : 'live');
});
element('window').addEventListener('change', redraw);
window.addEventListener('resize', redraw);
element('export').addEventListener('click', () => {
const csv = ['timestamp_utc,bytes_received_per_second,bytes_sent_per_second,messages_received_per_second,messages_sent_per_second', ...samples.map(sample => [new Date(sample.time).toISOString(), ...sample.values.map(value => value.toFixed(3))].join(','))].join('\r\n');
const url = URL.createObjectURL(new Blob([csv], {type:'text/csv;charset=utf-8'}));
const link = document.createElement('a'); link.href = url; link.download = 'connector-traffic.csv'; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
redraw(); poll();
</script>
</body>
</html>
@@ -0,0 +1,46 @@
using System.Diagnostics;
using System.Net.Sockets;
namespace EonaCat.Connections.Infrastructure
{
internal static class SocketKeepAliveConfigurator
{
public static void Configure(
Socket socket,
int keepAliveTimeSeconds,
int keepAliveIntervalSeconds,
int keepAliveRetryCount = 10)
{
if (socket == null)
{
return;
}
try
{
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
#if NET5_0_OR_GREATER
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Math.Max(1, keepAliveTimeSeconds));
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Math.Max(1, keepAliveIntervalSeconds));
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, Math.Max(1, keepAliveRetryCount));
#else
uint onOff = 1;
uint keepAliveTime = (uint)Math.Max(1, keepAliveTimeSeconds) * 1000;
uint keepAliveInterval = (uint)Math.Max(1, keepAliveIntervalSeconds) * 1000;
byte[] keepAliveSettings = new byte[12];
Buffer.BlockCopy(BitConverter.GetBytes(onOff), 0, keepAliveSettings, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(keepAliveTime), 0, keepAliveSettings, 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(keepAliveInterval), 0, keepAliveSettings, 8, 4);
socket.IOControl(IOControlCode.KeepAliveValues, keepAliveSettings, null);
#endif
}
catch (Exception exception)
{
Debug.WriteLine($"Failed to configure TCP keep-alive: {exception.Message}");
}
}
}
}
@@ -0,0 +1,108 @@
namespace EonaCat.Connections.Messaging
{
internal static class ResponseAwaiter
{
public static async Task<DataReceivedEventArgs?> WaitForSingleAsync(
Func<Task<bool>> sendAsync,
Action<EventHandler<DataReceivedEventArgs>> subscribe,
Action<EventHandler<DataReceivedEventArgs>> unsubscribe,
TimeSpan timeout,
Predicate<DataReceivedEventArgs>? responseFilter = null,
CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return null;
}
var completion = new TaskCompletionSource<DataReceivedEventArgs>(TaskCreationOptions.RunContinuationsAsynchronously);
void Handler(object? sender, DataReceivedEventArgs args)
{
if (responseFilter == null || responseFilter(args))
{
completion.TrySetResult(args);
}
}
subscribe(Handler);
try
{
if (!await sendAsync().ConfigureAwait(false))
{
return null;
}
using var timeoutSource = new CancellationTokenSource(timeout);
using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken);
using var registration = linkedSource.Token.Register(() => completion.TrySetCanceled());
try
{
return await completion.Task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return null;
}
}
finally
{
unsubscribe(Handler);
}
}
public static async Task<List<DataReceivedEventArgs>> WaitForManyAsync(
Func<Task<bool>> sendAsync,
Action<EventHandler<DataReceivedEventArgs>> subscribe,
Action<EventHandler<DataReceivedEventArgs>> unsubscribe,
TimeSpan timeout,
int expectedCount,
CancellationToken cancellationToken = default)
{
var responses = new List<DataReceivedEventArgs>(expectedCount);
if (expectedCount <= 0 || cancellationToken.IsCancellationRequested)
{
return responses;
}
var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
void Handler(object? sender, DataReceivedEventArgs args)
{
lock (responses)
{
if (responses.Count >= expectedCount)
{
return;
}
responses.Add(args);
if (responses.Count >= expectedCount)
{
completion.TrySetResult(true);
}
}
}
subscribe(Handler);
try
{
if (!await sendAsync().ConfigureAwait(false))
{
return responses;
}
using var timeoutSource = new CancellationTokenSource(timeout);
using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken);
using var registration = linkedSource.Token.Register(() => completion.TrySetResult(true));
await completion.Task.ConfigureAwait(false);
return responses;
}
finally
{
unsubscribe(Handler);
}
}
}
}
+108 -199
View File
@@ -1,41 +1,25 @@
using System.Diagnostics;
using EonaCat.Connections.Protocols;
using System.Diagnostics;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace EonaCat.Connections.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class Configuration : IDisposable
{
public event EventHandler<string> OnLog;
public List<string> TrustedThumbprints = new List<string>();
public bool EnableAutoReconnect { get; set; } = true;
public int ReconnectDelayInSeconds { get; set; } = 5;
public int MaxReconnectAttempts { get; set; } = 0; // 0 means unlimited attempts
public int SSLMaxRetries { get; set; } = 0; // 0 means unlimited attempts
public int SSLTimeoutInSeconds { get; set; } = 35;
public int MaxReconnectAttempts { get; set; } = 0;
public int SSLMaxRetries { get; set; } = 0;
public int SSLTimeoutInSeconds { get; set; } = 60;
public int SSLRetryDelayInSeconds { get; set; } = 5;
/// <summary>
/// Enables exponential backoff for SSL handshake retries.
/// When enabled, retry delays increase progressively: initial delay * (2 ^ attempt).
/// Caps out at SSLRetryDelayMaxSeconds to prevent excessive delays.
/// Default is false to provide instant retries after a fixed 5-second delay, allowing SSL handshakes up to 30 seconds to complete.
/// </summary>
public bool UseExponentialBackoffForSslRetries { get; set; } = false;
/// <summary>
/// Maximum delay in seconds for SSL handshake retries when exponential backoff is enabled. (default: 60)
/// </summary>
public int SSLRetryDelayMaxSeconds { get; set; } = 60;
/// <summary>
/// Enables diagnostic/tracing for SSL handshake process.
/// When enabled, detailed metrics and performance data are collected for each SSL connection attempt.
/// </summary>
public bool EnableSslDiagnostics { get; set; } = false;
public FramingMode MessageFraming { get; set; } = FramingMode.None;
@@ -48,27 +32,56 @@ namespace EonaCat.Connections.Models
public const string SSL_ERROR_SUFFIX = "[/SSL_ERROR]";
public ProtocolType Protocol { get; set; } = ProtocolType.TCP;
public Func<INetworkProtocol>? ProtocolFactory { get; set; }
public INetworkProtocol GetProtocol()
{
INetworkProtocol protocol;
if (ProtocolFactory != null)
{
protocol = ProtocolFactory();
}
else
{
protocol = EonaCat.Connections.Protocols.ProtocolFactory.CreateProtocol(Protocol);
}
protocol.ConfigureBufferSize(BufferSize);
protocol.ConfigureNagle(EnableNagle);
protocol.ConfigureRst(EnableRST);
if (protocol is IBroadcastConfigurableProtocol broadcastProtocol)
{
broadcastProtocol.ConfigureBroadcast(EnableBroadcast);
}
protocol.ConfigureKeepAlive(EnableKeepAlive, KeepAliveTimeSeconds, KeepAliveIntervalSeconds, KeepAliveRetryCount);
protocol.ConfigureSsl(UseSsl, Host, CheckCertificateRevocation, AllowTlsRenegotiation);
return protocol;
}
public int Port { get; set; } = 8080;
public string Host { get; set; } = "127.0.0.1";
public bool UseSsl => Certificate != null;
public X509Certificate2 Certificate { get; set; }
public X509Certificate2Collection AdditionalCertificates { get; set; }
public bool UseAesEncryption { get; set; } = false;
public int BufferSize { get; set; } = (int)BufferSizeMaximum.ExtraLarge;
public int MaxConnections { get; set; } = 100000;
public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);
public int BufferSize { get; set; } = (int)BufferSizeMaximum.Huge;
public int MAX_MESSAGE_SIZE { get; set; } = (int)MessageSizeMaximum.Default;
public int MaxConnections { get; set; } = 500000;
public TimeSpan ConnectionTimeout { get; set; } = Timeout.InfiniteTimeSpan;
public bool EnableKeepAlive { get; set; } = true;
public int KeepAliveTimeSeconds { get; set; } = 60;
public int KeepAliveIntervalSeconds { get; set; } = 10;
/// <summary>
/// Number of unacknowledged TCP keep-alive probes before the connection is considered dead. (default: 10)
/// </summary>
public int KeepAliveRetryCount { get; set; } = 10;
public bool EnableNagle { get; set; } = false;
// For testing purposes, allow self-signed certificates
public bool EnableBroadcast { get; set; }
public bool IsSelfSignedEnabled { get; set; }
public string AesPassword { get; set; }
@@ -82,132 +95,35 @@ namespace EonaCat.Connections.Models
public bool UseBigEndian { get; set; }
public int HeartbeatIntervalSeconds { get; set; } = 5;
public bool EnablePingPongLogs { get; set; }
public int MAX_MESSAGE_SIZE { get; set; } = 100 * 1024 * 1024; // 100 MB
public bool DisconnectOnMissedPong { get; set; }
public double IdleTimeoutSeconds { get; set; } = 30; // 0 means no idle timeout
public bool DisconectOnMissedPong { get; set; }
/// <summary>
/// Determines whether to enable RST (Reset) flag on socket close.
/// </summary>
public bool EnableRST { get; set; }
/// <summary>
/// Gets or sets the total bytes to read as a message prefix (if framing mode is LengthPrefixed) is enabled.
/// </summary>
/// <remarks>The length prefix index determines where the length information is read or written in
/// the buffer. Changing this value may affect how data is parsed or serialized, depending on the protocol or
/// format in use. (default: 4)</remarks>
public int LengthPrefixedLength { get; set; } = 4;
public bool EnableConnectionDebugLogs { get; set; }
/// <summary>
/// Enables automatic periodic generation of HTML status reports for errors and network health.
/// When enabled, reports are written to <see cref="HtmlReportOutputDirectory"/> every <see cref="HtmlReportIntervalSeconds"/> seconds.
/// </summary>
public bool EnableAutoHtmlReports { get; set; }
/// <summary>
/// The directory where auto-generated HTML reports are written. Defaults to "reports" under the current directory.
/// </summary>
public string HtmlReportOutputDirectory { get; set; } = Path.Combine(Directory.GetCurrentDirectory(), "reports");
/// <summary>
/// The interval in seconds between automatic HTML report generations. (default: 60)
/// </summary>
public int HtmlReportIntervalSeconds { get; set; } = 60;
/// <summary>
/// Enables automatic periodic generation of an HTML status page showing connected clients and throughput.
/// When enabled, the page is written to <see cref="HtmlReportOutputDirectory"/> every <see cref="ServerStatusPageIntervalSeconds"/> seconds.
/// Default is off.
/// </summary>
public bool EnableServerStatusPage { get; set; }
/// <summary>
/// The interval in seconds between automatic server status page generations. (default: 5)
/// </summary>
public int ServerStatusPageIntervalSeconds { get; set; } = 5;
/// <summary>
/// Enables a lightweight REST API that exposes health and status information via HTTP.
/// When enabled, the API listens on <see cref="HealthApiPort"/> (use 0 for a random available port).
/// Default is off.
/// </summary>
public bool EnableHealthApi { get; set; }
/// <summary>
/// The port for the health REST API. Use 0 (default) for a random available port.
/// The actual port can be retrieved from <c>NetworkServer.HealthApi.Port</c> or <c>NetworkClient.HealthApi.Port</c> after starting.
/// </summary>
public int HealthApiPort { get; set; } = 0;
/// <summary>
/// The IP address the health API server binds to.
/// Use <c>IPAddress.Any</c> (0.0.0.0) for Docker/container environments where the API must be reachable from outside the container.
/// Defaults to <c>IPAddress.Loopback</c> (127.0.0.1) for security.
/// </summary>
public IPAddress HealthApiBindAddress { get; set; } = IPAddress.Loopback;
/// <summary>
/// Write timeout in seconds for network operations. If a write operation takes longer than this duration, it will be aborted and an exception will be thrown. (default: 120 seconds)
/// </summary>
public double WriteTimeoutSeconds { get; set; } = 120;
public double WriteTimeoutSeconds { get; set; } = Timeout.Infinite;
/// <summary>
/// Read timeout in seconds for network operations. If a read operation takes longer than this duration, it will be aborted and an exception will be thrown. (default: 300 seconds)
/// </summary>
public double ReadTimeoutSeconds { get; set; } = 300;
public double ReadTimeoutSeconds { get; set; } = Timeout.Infinite;
// Security Settings (Protection against network attacks)
/// <summary>
/// Maximum accumulated message stream size in bytes before considering it a potential memory exhaustion attack.
/// Prevents decompression bombs and message accumulation attacks. (default: 500 MB)
/// </summary>
public long MaxMessageStreamSize { get; set; } = 500 * 1024 * 1024;
/// <summary>
/// Maximum number of messages allowed per client per second. 0 means unlimited. (default: 0)
/// Helps prevent flood/DoS attacks.
/// </summary>
public int MaxMessagesPerSecond { get; set; } = 0;
/// <summary>
/// Enable strict validation of length-prefixed messages to detect malformed packets. (default: true)
/// </summary>
public bool EnableLengthPrefixValidation { get; set; } = true;
/// <summary>
/// Enable rate limiting for UDP packets. 0 means unlimited. (default: 0)
/// </summary>
public int MaxUdpPacketsPerSecond { get; set; } = 0;
/// <summary>
/// Maximum HTTP request/response size for health API in bytes. (default: 10 MB)
/// </summary>
public int MaxHealthApiRequestSize { get; set; } = 10 * 1024 * 1024;
/// <summary>
/// Enable sanitization of error messages to prevent information leakage. (default: true)
/// When enabled, error details are hidden from clients.
/// </summary>
public bool EnableErrorMessageSanitization { get; set; } = true;
/// <summary>
/// Enable automatic cleanup of rate limit cache. (default: true)
/// </summary>
public bool EnableRateLimitCacheCleanup { get; set; } = true;
/// <summary>
/// Interval in seconds for cleaning up rate limit cache. (default: 300)
/// </summary>
public int RateLimitCacheCleanupIntervalSeconds { get; set; } = 300;
/// <summary>
/// Enable validation of HTTP headers to prevent header injection attacks. (default: true)
/// </summary>
public bool EnableHttpHeaderValidation { get; set; } = true;
public SecurityOptions Security { get; set; } = new SecurityOptions();
internal RemoteCertificateValidationCallback GetRemoteCertificateValidationCallback()
{
@@ -217,7 +133,7 @@ namespace EonaCat.Connections.Models
public void DisableInternalCertificateCheck()
{
CheckAgainstInternalTrustedCertificates = false;
OnLog?.Invoke(this, "Internal certificate check disabled.");
Debug.WriteLine("Internal certificate check disabled.");
}
private bool CertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
@@ -242,29 +158,6 @@ namespace EonaCat.Connections.Models
return result;
}
try
{
if (chain != null && certificate is X509Certificate2 cert)
{
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown |
X509VerificationFlags.IgnoreEndRevocationUnknown |
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.Build(cert);
foreach (var status in chain.ChainStatus)
{
OnLog?.Invoke(this, $"ChainStatus: {status.Status} - {status.StatusInformation}");
}
}
}
catch (Exception ex)
{
OnLog?.Invoke(this, $"Certificate validation succeeded in {stopwatch.ElapsedMilliseconds} ms");
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
reason = "Certificate validation succeeded";
@@ -272,52 +165,59 @@ namespace EonaCat.Connections.Models
return result;
}
if (CheckAgainstInternalTrustedCertificates && certificate is X509Certificate2 cert2)
if (certificate is X509Certificate2 cert2)
{
string thumbprint = cert2.Thumbprint?.Replace(" ", "").ToLowerInvariant();
if (!string.IsNullOrEmpty(thumbprint) && TrustedThumbprints.Contains(thumbprint))
if (CheckAgainstInternalTrustedCertificates &&
!string.IsNullOrEmpty(thumbprint) &&
TrustedThumbprints.Contains(thumbprint))
{
reason = $"Trusted thumbprint matched: {thumbprint}";
result = true;
return result;
}
reason = $"Certificate thumbprint not trusted: {thumbprint}";
result = false;
return result;
}
if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && chain != null)
if (!CheckAgainstInternalTrustedCertificates && cert2.Subject.Contains("localhost", StringComparison.OrdinalIgnoreCase))
{
bool fatal = false;
foreach (var status in chain.ChainStatus)
{
switch (status.Status)
{
case X509ChainStatusFlags.Revoked:
case X509ChainStatusFlags.NotSignatureValid:
fatal = true;
reason = $"Fatal chain error: {status.Status} - {status.StatusInformation}";
break;
}
if (fatal)
{
break;
}
}
if (!fatal)
{
reason = "Certificate accepted (ignoring non-fatal chain warnings)";
reason = $"Local development certificate accepted: {thumbprint}";
result = true;
return result;
}
}
result = false;
return result;
try
{
if (chain != null && certificate is X509Certificate2 cert)
{
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
chain.Build(cert);
var fatalChainErrors = chain.ChainStatus
.Where(status => status.Status != X509ChainStatusFlags.NoError &&
status.Status != X509ChainStatusFlags.UntrustedRoot &&
status.Status != X509ChainStatusFlags.PartialChain)
.ToArray();
if (fatalChainErrors.Length == 0 && sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
{
reason = "Certificate chain warnings are not accepted without an explicit trusted thumbprint.";
return false;
}
if (fatalChainErrors.Length > 0)
{
reason = $"Fatal chain error: {string.Join(", ", fatalChainErrors.Select(status => $"{status.Status} ({status.StatusInformation.Trim()})"))}";
return false;
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Chain validation exception: {ex}");
reason = $"Certificate validation exception: {ex}";
return false;
}
reason = $"Certificate rejected: {sslPolicyErrors}";
@@ -334,24 +234,19 @@ namespace EonaCat.Connections.Models
{
stopwatch.Stop();
OnLog?.Invoke(this,
Debug.WriteLine(
$"Certificate validation result={result}. " +
$"Reason={reason}. " +
$"Duration={stopwatch.ElapsedMilliseconds} ms");
}
}
/// <summary>
/// Detects whether the application is running inside a Docker container.
/// </summary>
public static bool IsRunningInContainer =>
Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true" ||
File.Exists("/.dockerenv");
/// <summary>
/// Configures the settings for use in a Docker/container environment.
/// Sets the host to 0.0.0.0 and the health API bind address to <c>IPAddress.Any</c>.
/// </summary>
public bool EnableDualStack { get; set; }
public Configuration UseContainerDefaults()
{
Host = "0.0.0.0";
@@ -359,11 +254,6 @@ namespace EonaCat.Connections.Models
return this;
}
/// <summary>
/// Calculates the SSL retry delay for a given attempt number, accounting for exponential backoff if enabled.
/// </summary>
/// <param name="attemptNumber">The attempt number (1-based).</param>
/// <returns>The delay in seconds.</returns>
public int GetSslRetryDelaySeconds(int attemptNumber)
{
if (!UseExponentialBackoffForSslRetries || attemptNumber <= 1)
@@ -371,14 +261,33 @@ namespace EonaCat.Connections.Models
return SSLRetryDelayInSeconds;
}
// Exponential backoff: baseDelay * 2^(attempt-1), capped at max
var exponentialDelay = SSLRetryDelayInSeconds * Math.Pow(2, attemptNumber - 1);
return (int)Math.Min(exponentialDelay, SSLRetryDelayMaxSeconds);
}
public Configuration UseHighScaleProduction()
{
MaxConnections = 1000000;
EnableConnectionDebugLogs = false;
EnablePingPongLogs = false;
KeepAliveTimeSeconds = 30;
KeepAliveIntervalSeconds = 5;
return this;
}
public Configuration UseDistributedProduction()
{
MaxConnections = 500000;
EnableConnectionDebugLogs = false;
EnableNagle = false;
EnableRST = true;
return this;
}
public void Dispose()
{
Certificate?.Dispose();
}
}
}
+53 -53
View File
@@ -1,14 +1,13 @@
using System.Net;
using EonaCat.Connections.ConnectionDiagnostics;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Channels;
using EonaCat.Connections.Security;
namespace EonaCat.Connections.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class Connection : IDisposable, IAsyncDisposable
{
public string Id { get; set; }
@@ -48,11 +47,9 @@ namespace EonaCat.Connections.Models
return false;
}
// Send a zero-byte packet to check if the connection is still alive
try
{
socket.Send(Array.Empty<byte>(), 0, 0);
LastActive = DateTime.UtcNow;
}
catch
{
@@ -71,6 +68,8 @@ namespace EonaCat.Connections.Models
public DateTime ConnectedAt { get; internal set; }
private long _lastActiveTicks;
private long _lastDataSentTicks;
private long _lastDataReceivedTicks;
public DateTime LastActive
{
@@ -79,15 +78,41 @@ namespace EonaCat.Connections.Models
}
public DateTime DisconnectionTime { get; internal set; }
public DateTime LastDataSent { get; internal set; }
public DateTime LastDataReceived { get; internal set; }
public DateTime LastDataSent
{
get => new DateTime(Interlocked.Read(ref _lastDataSentTicks));
internal set => Interlocked.Exchange(ref _lastDataSentTicks, value.Ticks);
}
public DateTime LastDataReceived
{
get => new DateTime(Interlocked.Read(ref _lastDataReceivedTicks));
internal set => Interlocked.Exchange(ref _lastDataReceivedTicks, value.Ticks);
}
private long _securityViolationCount;
private long _rateLimitViolations;
public long SecurityViolationCount
{
get => Interlocked.Read(ref _securityViolationCount);
set => Interlocked.Exchange(ref _securityViolationCount, value);
}
public long RateLimitViolations
{
get => Interlocked.Read(ref _rateLimitViolations);
set => Interlocked.Exchange(ref _rateLimitViolations, value);
}
public void IncrementRateLimitViolations() => Interlocked.Increment(ref _rateLimitViolations);
public RateLimiter OutgoingRateLimiter { get; set; }
public Channel<byte[]> SendQueue =
Channel.CreateBounded<byte[]>(new BoundedChannelOptions(8192)
{
SingleReader = true,
SingleWriter = false,
//FullMode = BoundedChannelFullMode.DropOldest
});
public TimeSpan IdleTime() => DateTime.UtcNow - LastActive;
@@ -117,34 +142,13 @@ namespace EonaCat.Connections.Models
bool includeSeconds = true,
bool includeMilliseconds = true)
{
var parts = new List<string>();
if (includeDays)
{
parts.Add($"{(int)span.TotalDays:D2}d");
}
if (includeHours)
{
parts.Add($"{span.Hours:D2}h");
}
if (includeMinutes)
{
parts.Add($"{span.Minutes:D2}m");
}
if (includeSeconds)
{
parts.Add($"{span.Seconds:D2}s");
}
if (includeMilliseconds)
{
parts.Add($"{span.Milliseconds:D3}ms");
}
return string.Join(" ", parts);
return ConnectionTimeFormatter.Format(
span,
includeDays,
includeHours,
includeMinutes,
includeSeconds,
includeMilliseconds);
}
public string IdleTimeFormatted(bool days = true, bool hours = true, bool minutes = true, bool seconds = true, bool ms = true)
@@ -177,10 +181,6 @@ namespace EonaCat.Connections.Models
public Task? SendLoopTask;
public Task ReceiveDataTask { get; internal set; }
public bool IsIdleTimeoutTriggered { get; internal set; }
public DateTime LastIdleLogUtc { get; internal set; }
public double ShowIdleReminderInSeconds { get; set; } = 20;
public bool IsClosing { get; internal set; }
private bool _disposed;
@@ -202,7 +202,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
SendQueue.Writer.TryComplete();
@@ -237,7 +237,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
SendQueue.Writer.TryComplete();
@@ -254,7 +254,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
try
@@ -263,7 +263,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
try
@@ -273,7 +273,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
try
@@ -282,7 +282,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
try
@@ -291,7 +291,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
try
@@ -300,7 +300,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
Metadata.Clear();
@@ -328,7 +328,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
try
@@ -337,7 +337,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
try
@@ -346,7 +346,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
}
@@ -358,7 +358,7 @@ namespace EonaCat.Connections.Models
}
catch
{
// Do nothing
}
}
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more