diff --git a/FmiSrl.FtpServer.Server/Abstractions/FtpCommandContext.cs b/FmiSrl.FtpServer.Server/Abstractions/FtpCommandContext.cs
index d1c2c2b..b0448d5 100644
--- a/FmiSrl.FtpServer.Server/Abstractions/FtpCommandContext.cs
+++ b/FmiSrl.FtpServer.Server/Abstractions/FtpCommandContext.cs
@@ -1,3 +1,4 @@
+using FmiSrl.FtpServer.Server.Infrastructure;
using Microsoft.Extensions.Logging;
namespace FmiSrl.FtpServer.Server.Abstractions;
@@ -13,6 +14,12 @@ namespace FmiSrl.FtpServer.Server.Abstractions;
/// The server configuration options.
/// The logger to use for recording command execution details.
/// The collection of registered FTP server event handlers.
+///
+/// The server-wide that PASV leases data ports from, or null
+/// to let the command build a throwaway pool from . Supplying the
+/// shared pool is what stops two concurrent sessions from being handed the same port; the
+/// null fallback exists only for contexts constructed by hand outside a running server.
+///
public record FtpCommandContext(
IFtpSession Session,
string Verb,
@@ -21,7 +28,8 @@ public record FtpCommandContext(
IAuthenticationProvider Authenticator,
FtpServerConfigurationOptions Configuration,
ILogger Logger,
- IEnumerable? EventHandlers = null
+ IEnumerable? EventHandlers = null,
+ PassivePortPool? PassivePorts = null
)
{
///
diff --git a/FmiSrl.FtpServer.Server/Commands/PasvCommand.cs b/FmiSrl.FtpServer.Server/Commands/PasvCommand.cs
index bbdd793..a8299ad 100644
--- a/FmiSrl.FtpServer.Server/Commands/PasvCommand.cs
+++ b/FmiSrl.FtpServer.Server/Commands/PasvCommand.cs
@@ -3,6 +3,7 @@
using System.Net.Sockets;
using FmiSrl.FtpServer.Server.Abstractions;
using FmiSrl.FtpServer.Server.Infrastructure;
+using Microsoft.Extensions.Logging;
namespace FmiSrl.FtpServer.Server.Commands;
@@ -25,25 +26,79 @@ public async Task ExecuteAsync(FtpCommandContext context)
private static async Task PrepareDataConnectionAsync(FtpCommandContext context)
{
- if (context.Session.DataConnection != null)
+ await ReleasePreviousDataConnectionAsync(context);
+
+ var dataConnection = await TryOpenDataConnectionAsync(context);
+ if (dataConnection is null)
{
- await context.Session.DataConnection.DisposeAsync();
+ return;
}
- var clientIp = (context.Session.RemoteEndPoint as IPEndPoint)?.Address.ToString() ?? "";
- Console.WriteLine($"[PASV-V2] PasvCommand: ListeningIp='{context.Configuration.ListeningIp}', clientIp='{clientIp}', portRange={context.Configuration.PasvMinPort}-{context.Configuration.PasvMaxPort}");
+ context.Session.DataConnection = dataConnection;
+ await SendPassiveModeResponseAsync(context, dataConnection.Port);
+ }
- var dataConnection = new MikuPassiveDataConnection(
- context.Configuration.ListeningIp,
- context.Configuration.PasvMinPort,
- context.Configuration.PasvMaxPort,
- clientIp
- );
+ ///
+ /// The session's reference is cleared before the old connection is disposed, so a failure to
+ /// release the previous port cannot leave the session pointing at a dead connection that every
+ /// later transfer command would then try to use.
+ ///
+ private static async Task ReleasePreviousDataConnectionAsync(FtpCommandContext context)
+ {
+ var previousConnection = context.Session.DataConnection;
+ if (previousConnection is null)
+ {
+ return;
+ }
- context.Session.DataConnection = dataConnection;
+ context.Session.DataConnection = null;
- await SendPassiveModeResponseAsync(context, dataConnection.Port);
+ try
+ {
+ await previousConnection.DisposeAsync();
+ }
+ catch (Exception exception)
+ {
+ context.Logger.LogWarning(exception, "Failed to release the previous passive data connection");
+ }
}
+
+ private static async Task TryOpenDataConnectionAsync(FtpCommandContext context)
+ {
+ try
+ {
+ return OpenDataConnection(context);
+ }
+ catch (Exception exception)
+ {
+ context.Logger.LogError(exception, "Failed to open a passive data connection");
+ await context.Session.SendResponseAsync(425, "Can't open data connection.");
+ return null;
+ }
+ }
+
+ private static PassiveDataConnection OpenDataConnection(FtpCommandContext context)
+ {
+ var configuration = context.Configuration;
+ var pool = context.PassivePorts ?? new PassivePortPool(configuration, context.Logger);
+ var clientIp = (context.Session.RemoteEndPoint as IPEndPoint)?.Address.ToString() ?? "";
+
+ var portLease = pool.Bind();
+ try
+ {
+ return new PassiveDataConnection(
+ portLease,
+ clientIp,
+ configuration.PasvIdleTimeout,
+ context.Logger);
+ }
+ catch
+ {
+ portLease.Dispose();
+ throw;
+ }
+ }
+
private static async Task SendPassiveModeResponseAsync(FtpCommandContext context, int port)
{
var localIp = GetLocalIpAddress(context.Session.RemoteEndPoint);
@@ -51,7 +106,6 @@ private static async Task SendPassiveModeResponseAsync(FtpCommandContext context
var p1 = port / 256;
var p2 = port % 256;
- Console.WriteLine($"[PASV-V2] PasvCommand: advertising 227 with IP={localIp}, port={port} ({p1},{p2})");
await context.Session.SendResponseAsync(227, $"Entering Passive Mode ({localIp},{p1},{p2}).");
}
diff --git a/FmiSrl.FtpServer.Server/FmiSrl.FtpServer.Server.csproj b/FmiSrl.FtpServer.Server/FmiSrl.FtpServer.Server.csproj
index 477f83c..36a82f3 100644
--- a/FmiSrl.FtpServer.Server/FmiSrl.FtpServer.Server.csproj
+++ b/FmiSrl.FtpServer.Server/FmiSrl.FtpServer.Server.csproj
@@ -9,13 +9,16 @@
FMI S.r.l.
Copyright 2026 FMI S.r.l.
-
+
-
+
+
+
+
diff --git a/FmiSrl.FtpServer.Server/FtpServer.cs b/FmiSrl.FtpServer.Server/FtpServer.cs
index 90ec803..abbc628 100644
--- a/FmiSrl.FtpServer.Server/FtpServer.cs
+++ b/FmiSrl.FtpServer.Server/FtpServer.cs
@@ -43,6 +43,12 @@ public class FtpServer(
private readonly FtpCommandHandler _commandHandler = new(middlewares);
private readonly ConcurrentDictionary _sessions = new();
+ ///
+ /// One pool for the whole server: passive ports are a resource shared by every session, so the
+ /// bookkeeping that keeps two sessions off the same port has to be shared too.
+ ///
+ private readonly PassivePortPool _passivePorts = new(configurationOptions.Value, logger);
+
private NetServer? _netServer;
private void RegisterCommands()
@@ -189,7 +195,8 @@ private async Task ExecuteCommandAsync(NetClient client, FtpSession session, str
_authenticationProvider,
_configurationOptions,
_logger,
- _eventHandlers);
+ _eventHandlers,
+ _passivePorts);
await _commandHandler.HandleCommandAsync(context);
diff --git a/FmiSrl.FtpServer.Server/FtpServerConfigurationOptions.cs b/FmiSrl.FtpServer.Server/FtpServerConfigurationOptions.cs
index 23ed839..21eeccd 100644
--- a/FmiSrl.FtpServer.Server/FtpServerConfigurationOptions.cs
+++ b/FmiSrl.FtpServer.Server/FtpServerConfigurationOptions.cs
@@ -24,17 +24,41 @@ public class FtpServerConfigurationOptions
///
/// Gets or sets the minimum port number in the range for passive data connections.
///
- /// The minimum passive port as an . Defaults to 50000.
- [Range(1, 65535)]
+ ///
+ /// The minimum passive port as an . Defaults to 50000. Set it to 0 to use no
+ /// range at all and let the operating system assign an ephemeral port per data connection,
+ /// which is only appropriate when no firewall or NAT rule constrains the passive ports.
+ ///
+ ///
+ /// Size the range for the peak number of concurrent transfers, with headroom: each finished
+ /// download keeps its port in TIME_WAIT for a while afterwards. The server logs a
+ /// warning and falls back to an ephemeral port whenever the range runs dry.
+ ///
+ [Range(0, 65535)]
public int PasvMinPort { get; set; } = 50000;
///
/// Gets or sets the maximum port number in the range for passive data connections.
///
- /// The maximum passive port as an . Defaults to 50100.
- [Range(1, 65535)]
+ /// The maximum passive port as an . Defaults to 50100. Must not be lower than .
+ [Range(0, 65535)]
public int PasvMaxPort { get; set; } = 50100;
+ ///
+ /// Gets or sets how long a passive listener waits for the client's data connection before the
+ /// port is reclaimed.
+ ///
+ ///
+ /// The wait as a . Defaults to two minutes. Set it to
+ /// to wait indefinitely, which risks draining the
+ /// passive range whenever clients issue PASV and then abandon the transfer.
+ ///
+ ///
+ /// The timer only covers the wait for the client to dial in; it is disarmed once the data
+ /// connection is accepted and therefore never cuts a slow transfer short.
+ ///
+ public TimeSpan PasvIdleTimeout { get; set; } = TimeSpan.FromMinutes(2);
+
///
/// Gets or sets the name of the FTP server presented in the welcome message.
///
diff --git a/FmiSrl.FtpServer.Server/Infrastructure/MikuClientStream.cs b/FmiSrl.FtpServer.Server/Infrastructure/MikuClientStream.cs
deleted file mode 100644
index 566613d..0000000
--- a/FmiSrl.FtpServer.Server/Infrastructure/MikuClientStream.cs
+++ /dev/null
@@ -1,252 +0,0 @@
-using System.Threading.Channels;
-using Miku.Core;
-
-namespace FmiSrl.FtpServer.Server.Infrastructure;
-
-///
-/// Provides a stream implementation that wraps a for reading and writing data.
-///
-public class MikuClientStream : Stream
-{
- private readonly NetClient _client;
-
- private readonly Channel _readChannel = Channel.CreateBounded(
- new BoundedChannelOptions(128)
- {
- FullMode = BoundedChannelFullMode.Wait, SingleReader = true, SingleWriter = true
- });
-
- private byte[]? _currentReadBuffer;
- private int _currentReadBufferPosition;
- private bool _isDisposed;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The to wrap.
- public MikuClientStream(NetClient client)
- {
- _client = client;
- }
-
- ///
- /// Enqueues data received from the client for reading from the stream.
- ///
- /// The data to enqueue.
- public void EnqueueData(ReadOnlyMemory data)
- {
- if (data.Length == 0)
- {
- _readChannel.Writer.TryComplete();
- return;
- }
- _readChannel.Writer.TryWrite(data.ToArray());
- }
-
- ///
- /// Completes the reading channel, indicating no more data will be received.
- ///
- public void Complete()
- {
- _readChannel.Writer.TryComplete();
- }
-
- ///
- public override bool CanRead => true;
-
- ///
- public override bool CanSeek => false;
-
- ///
- public override bool CanWrite => true;
-
- ///
- public override long Length => throw new NotSupportedException();
-
- ///
- public override long Position
- {
- get => throw new NotSupportedException();
- set => throw new NotSupportedException();
- }
-
- ///
- public override void Flush()
- {
- // Simple wait for library to finish background tasks
- var timeout = 0;
- while (_client.HasPendingSends && timeout < 200)// 10 seconds max
- {
- Thread.Sleep(50);
- timeout++;
- }
- }
-
- ///
- public override async Task FlushAsync(CancellationToken cancellationToken)
- {
- var timeout = 0;
- while (_client.HasPendingSends && timeout < 200)
- {
- await Task.Delay(50, cancellationToken);
- timeout++;
- }
- }
-
- ///
- public override int Read(byte[] buffer, int offset, int count) =>
- ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
-
- ///
- public override async Task ReadAsync(
- byte[] buffer,
- int offset,
- int count,
- CancellationToken cancellationToken
- ) => await ReadAsync(buffer.AsMemory(offset, count), cancellationToken);
-
- ///
- public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
- {
- if (_currentReadBuffer == null || _currentReadBufferPosition >= _currentReadBuffer.Length)
- {
- try
- {
- if (await _readChannel.Reader.WaitToReadAsync(cancellationToken))
- {
- if (_readChannel.Reader.TryRead(out var chunk))
- {
- _currentReadBuffer = chunk;
- _currentReadBufferPosition = 0;
- }
- }
- else
- {
- return 0;// EOF
- }
- }
- catch (ChannelClosedException)
- {
- return 0;
- }
- }
-
- if (_currentReadBuffer != null && _currentReadBufferPosition < _currentReadBuffer.Length)
- {
- var available = _currentReadBuffer.Length - _currentReadBufferPosition;
- var toCopy = Math.Min(available, buffer.Length);
- _currentReadBuffer.AsSpan(_currentReadBufferPosition, toCopy).CopyTo(buffer.Span);
- _currentReadBufferPosition += toCopy;
- return toCopy;
- }
-
- return 0;
- }
-
- ///
- public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
-
- ///
- public override void SetLength(long value) => throw new NotSupportedException();
-
- ///
- public override void Write(byte[] buffer, int offset, int count)
- {
- if (count == 0)
- {
- return;
- }
-
- // Blocking wait for backpressure
- var backoff = 0;
- while (_client.HasPendingSends && backoff < 100)
- {
- Thread.Sleep(10);
- backoff++;
- }
-
- var data = new byte[count];
- Buffer.BlockCopy(
- buffer,
- offset,
- data,
- 0,
- count);
- _client.Send(data);
- }
-
- ///
- public override async Task WriteAsync(
- byte[] buffer,
- int offset,
- int count,
- CancellationToken cancellationToken
- )
- {
- await WriteAsync(buffer.AsMemory(offset, count), cancellationToken);
- }
-
- ///
- public override async ValueTask WriteAsync(
- ReadOnlyMemory buffer,
- CancellationToken cancellationToken = default
- )
- {
- if (buffer.Length == 0)
- {
- return;
- }
-
- // Break large writes into smaller chunks to help Miku's internal buffers
- const int chunkSize = 16384;
- var processed = 0;
- while (processed < buffer.Length)
- {
- var toSend = Math.Min(chunkSize, buffer.Length - processed);
-
- // Wait for backpressure
- var backoff = 0;
- while (_client.HasPendingSends && backoff < 50)
- {
- await Task.Delay(10, cancellationToken);
- backoff++;
- }
-
- var data = buffer.Slice(processed, toSend).ToArray();
- _client.Send(data);
- processed += toSend;
- }
- }
-
- ///
- public override async ValueTask DisposeAsync()
- {
- if (_isDisposed)
- {
- return;
- }
- _isDisposed = true;
-
- // Ensure everything is sent before we kill the client
- await FlushAsync(default);
- await Task.Delay(500);
-
- try { _client.Stop(); }
- catch {}
- await base.DisposeAsync();
- }
-
- ///
- protected override void Dispose(bool disposing)
- {
- if (!_isDisposed && disposing)
- {
- _isDisposed = true;
- Flush();
- Thread.Sleep(500);
- try { _client.Stop(); }
- catch {}
- }
- base.Dispose(disposing);
- }
-}
diff --git a/FmiSrl.FtpServer.Server/Infrastructure/MikuPassiveDataConnection.cs b/FmiSrl.FtpServer.Server/Infrastructure/MikuPassiveDataConnection.cs
deleted file mode 100644
index 141cf93..0000000
--- a/FmiSrl.FtpServer.Server/Infrastructure/MikuPassiveDataConnection.cs
+++ /dev/null
@@ -1,170 +0,0 @@
-using System.Net;
-using System.Net.NetworkInformation;
-using System.Net.Sockets;
-using FmiSrl.FtpServer.Server.Abstractions;
-
-namespace FmiSrl.FtpServer.Server.Infrastructure;
-
-///
-/// Provides an implementation of that listens for a passive
-/// data connection using a plain and exposes the accepted socket
-/// as a . The name is retained for backwards compatibility.
-///
-public class MikuPassiveDataConnection : IFtpDataConnection
-{
- private readonly TcpListener _listener;
- private readonly string _authorizedClientIp;
- private readonly CancellationTokenSource _cts = new();
- private TcpClient? _acceptedClient;
- private NetworkStream? _networkStream;
- private bool _disposed;
-
- ///
- /// Gets the port the data listener is bound to.
- ///
- public int Port { get; }
-
- ///
- /// Initializes a new instance of the class and
- /// binds a listener on the first available port in the configured range.
- ///
- /// The IP address to bind the data listener to.
- /// Minimum port in the passive range.
- /// Maximum port in the passive range.
- /// The only client IP that may complete the data connection.
- public MikuPassiveDataConnection(string ip, int minPort, int maxPort, string authorizedClientIp)
- {
- _authorizedClientIp = authorizedClientIp;
- var bindAddress = IPAddress.TryParse(ip, out var parsed) ? parsed : IPAddress.Any;
-
- _listener = BindInRange(bindAddress, minPort, maxPort);
-
- // If anything below throws, release the bound listener before the exception escapes;
- // otherwise the partially-initialised instance leaks a socket that only closes on GC
- // (and TcpListener has no finalizer that will close it for us).
- try
- {
- Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
- Console.WriteLine($"[PASV-V2] TcpListener bound on {bindAddress}:{Port} (authorized={authorizedClientIp})");
- }
- catch
- {
- try { _listener.Stop(); } catch { /* best effort */ }
- throw;
- }
- }
-
- private static TcpListener BindInRange(IPAddress address, int minPort, int maxPort)
- {
- // On Windows, a specific-IP listener (e.g. 127.0.0.1:port) shadows a wildcard
- // listener (0.0.0.0:port) for connections to that specific IP. `TcpListener.Start()`
- // still succeeds on the wildcard, but the client's connection is delivered to the
- // more-specific socket. Enumerate all active listeners and skip any port that
- // already has a binding on any IP.
- var busyPorts = new HashSet(
- IPGlobalProperties.GetIPGlobalProperties()
- .GetActiveTcpListeners()
- .Select(ep => ep.Port));
-
- for (var port = minPort; port <= maxPort; port++)
- {
- if (busyPorts.Contains(port))
- {
- continue;
- }
-
- try
- {
- var listener = new TcpListener(address, port);
- listener.Start();
- return listener;
- }
- catch (SocketException)
- {
- // Port became busy between the enumeration and Start(); try the next.
- }
- }
-
- // Range exhausted — fall back to an ephemeral port. This is a warning-level event:
- // sustained fallbacks indicate the configured PASV range is too small or held by
- // other processes, and eventually the OS-wide dynamic port range will be pressured too.
- var fallback = new TcpListener(address, 0);
- fallback.Start();
- var fallbackPort = ((IPEndPoint)fallback.LocalEndpoint).Port;
- Console.WriteLine($"[PASV-V2] WARNING: configured range {minPort}-{maxPort} exhausted, fell back to ephemeral port {fallbackPort}");
- return fallback;
- }
-
- ///
- public async Task GetStreamAsync()
- {
- Console.WriteLine($"[PASV-V2] Awaiting client accept on port {Port}");
- _acceptedClient = await _listener.AcceptTcpClientAsync(_cts.Token).ConfigureAwait(false);
-
- var remoteEndpoint = (IPEndPoint?)_acceptedClient.Client.RemoteEndPoint;
- var clientIp = remoteEndpoint?.Address.ToString() ?? "";
- Console.WriteLine($"[PASV-V2] Accepted client from {clientIp} (port {Port}, authorized={_authorizedClientIp})");
-
- if (!AreIpAddressesEqual(clientIp, _authorizedClientIp))
- {
- Console.WriteLine($"[PASV-V2] REJECTED: {clientIp} != {_authorizedClientIp}");
- _acceptedClient.Close();
- _acceptedClient = null;
- throw new UnauthorizedAccessException(
- $"Data connection from {clientIp} rejected. Expected {_authorizedClientIp}.");
- }
-
- _networkStream = _acceptedClient.GetStream();
- Console.WriteLine($"[PASV-V2] NetworkStream ready (port {Port})");
- return _networkStream;
- }
-
- ///
- public async ValueTask DisposeAsync()
- {
- if (_disposed)
- {
- return;
- }
- _disposed = true;
- Console.WriteLine($"[PASV-V2] Disposing (port {Port})");
-
- try { _cts.Cancel(); } catch { /* best effort */ }
-
- if (_networkStream is not null)
- {
- try { await _networkStream.DisposeAsync().ConfigureAwait(false); } catch { /* best effort */ }
- }
-
- try { _acceptedClient?.Close(); } catch { /* best effort */ }
- try { _listener.Stop(); } catch { /* best effort */ }
-
- _cts.Dispose();
- Console.WriteLine($"[PASV-V2] Disposed (port {Port})");
- }
-
- private static bool AreIpAddressesEqual(string ip1, string ip2)
- {
- if (ip1 == ip2)
- {
- return true;
- }
- if (string.IsNullOrEmpty(ip1) || string.IsNullOrEmpty(ip2))
- {
- return false;
- }
-
- if (IPAddress.TryParse(ip1, out var addr1) && IPAddress.TryParse(ip2, out var addr2))
- {
- if (addr1.Equals(addr2))
- {
- return true;
- }
-
- // Normalize IPv4-mapped IPv6 addresses.
- return addr1.MapToIPv6().Equals(addr2.MapToIPv6());
- }
-
- return false;
- }
-}
diff --git a/FmiSrl.FtpServer.Server/Infrastructure/PassiveDataConnection.cs b/FmiSrl.FtpServer.Server/Infrastructure/PassiveDataConnection.cs
new file mode 100644
index 0000000..9ac656b
--- /dev/null
+++ b/FmiSrl.FtpServer.Server/Infrastructure/PassiveDataConnection.cs
@@ -0,0 +1,200 @@
+using System.Net;
+using System.Net.Sockets;
+using FmiSrl.FtpServer.Server.Abstractions;
+using Microsoft.Extensions.Logging;
+
+namespace FmiSrl.FtpServer.Server.Infrastructure;
+
+///
+/// An that waits on a leased passive port and exposes the
+/// accepted client socket as a .
+///
+///
+/// The connection gives up its port on its own if the client never dials in. A client that issues
+/// PASV and then walks away — an aborted transfer, a dropped network, a half-open control
+/// connection — would otherwise pin its port until the session is torn down, and a server whose
+/// sessions are stuck that way exhausts the passive range without ever transferring a byte. The
+/// watchdog is disarmed as soon as a client is accepted, so it never interrupts a slow transfer.
+///
+public sealed class PassiveDataConnection : IFtpDataConnection
+{
+ private const int AwaitingClient = 0;
+ private const int ClientAccepted = 1;
+ private const int Abandoned = 2;
+
+ private readonly PassivePortLease _portLease;
+ private readonly string _authorizedClientIp;
+ private readonly TimeSpan _idleTimeout;
+ private readonly CancellationTokenSource _acceptCts = new();
+ private readonly ILogger? _logger;
+ private readonly Timer? _idleWatchdog;
+ private TcpClient? _acceptedClient;
+ private NetworkStream? _networkStream;
+ private int _acceptState = AwaitingClient;
+ private int _disposed;
+
+ ///
+ /// Gets the port the data listener is bound to.
+ ///
+ /// The local port as an , to be advertised to the client in the 227 reply.
+ public int Port => _portLease.Port;
+
+ ///
+ /// Waits for the authorized client on an already-bound passive port.
+ ///
+ ///
+ /// The holding the started listener. This connection takes
+ /// ownership of it and disposes it, releasing the port, when the transfer ends or is abandoned.
+ ///
+ /// The only client IP allowed to complete the data connection.
+ ///
+ /// How long to wait for the client's data connection before releasing the port. Use
+ /// , or any non-positive value, to wait indefinitely.
+ ///
+ /// An optional used to report abandoned connections.
+ public PassiveDataConnection(
+ PassivePortLease portLease,
+ string authorizedClientIp,
+ TimeSpan idleTimeout,
+ ILogger? logger = null)
+ {
+ ArgumentNullException.ThrowIfNull(portLease);
+
+ _portLease = portLease;
+ _authorizedClientIp = authorizedClientIp;
+ _idleTimeout = idleTimeout;
+ _logger = logger;
+ _idleWatchdog = StartIdleWatchdog(idleTimeout);
+ }
+
+ ///
+ /// No client connected within the configured idle timeout.
+ /// A host other than the authorized client connected.
+ public async Task GetStreamAsync()
+ {
+ _acceptedClient = await AcceptAuthorizedClientAsync().ConfigureAwait(false);
+ _networkStream = _acceptedClient.GetStream();
+ return _networkStream;
+ }
+
+ ///
+ public async ValueTask DisposeAsync()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) == 1)
+ {
+ return;
+ }
+
+ if (_idleWatchdog is not null)
+ {
+ await _idleWatchdog.DisposeAsync().ConfigureAwait(false);
+ }
+
+ await CancelPendingAcceptAsync().ConfigureAwait(false);
+
+ if (_networkStream is not null)
+ {
+ try { await _networkStream.DisposeAsync().ConfigureAwait(false); } catch { /* best effort */ }
+ }
+
+ try { _acceptedClient?.Dispose(); } catch { /* best effort */ }
+
+ _portLease.Dispose();
+ _acceptCts.Dispose();
+ }
+
+ private Timer? StartIdleWatchdog(TimeSpan idleTimeout) =>
+ idleTimeout <= TimeSpan.Zero
+ ? null
+ : new Timer(_ => AbandonUnusedPort(), state: null, idleTimeout, Timeout.InfiniteTimeSpan);
+
+ private void AbandonUnusedPort()
+ {
+ if (Interlocked.CompareExchange(ref _acceptState, Abandoned, AwaitingClient) != AwaitingClient)
+ {
+ return;
+ }
+
+ _logger?.LogWarning(
+ "No data connection was established on passive port {Port} within {IdleTimeout}; releasing the port",
+ _portLease.Port,
+ _idleTimeout);
+
+ try { _acceptCts.Cancel(); } catch { /* best effort */ }
+ _portLease.Dispose();
+ }
+
+ private async Task AcceptAuthorizedClientAsync()
+ {
+ var client = await AcceptClientBeforeIdleTimeoutAsync().ConfigureAwait(false);
+ var clientIp = (client.Client.RemoteEndPoint as IPEndPoint)?.Address.ToString() ?? "";
+
+ if (AreIpAddressesEqual(clientIp, _authorizedClientIp))
+ {
+ return client;
+ }
+
+ client.Dispose();
+ throw new UnauthorizedAccessException(
+ $"Data connection from {clientIp} rejected. Expected {_authorizedClientIp}.");
+ }
+
+ private async Task AcceptClientBeforeIdleTimeoutAsync()
+ {
+ try
+ {
+ var client = await _portLease.Listener.AcceptTcpClientAsync(_acceptCts.Token).ConfigureAwait(false);
+ return DisarmWatchdogOrDiscard(client);
+ }
+ catch (Exception exception) when (IsAbandonedAccept(exception))
+ {
+ throw new TimeoutException(
+ $"No data connection was established on passive port {_portLease.Port} within {_idleTimeout}.");
+ }
+ }
+
+ private TcpClient DisarmWatchdogOrDiscard(TcpClient client)
+ {
+ if (Interlocked.CompareExchange(ref _acceptState, ClientAccepted, AwaitingClient) != AwaitingClient)
+ {
+ client.Dispose();
+ throw new TimeoutException(
+ $"The data connection on passive port {_portLease.Port} was abandoned before it could be used.");
+ }
+
+ _idleWatchdog?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
+ return client;
+ }
+
+ private bool IsAbandonedAccept(Exception exception) =>
+ exception is OperationCanceledException or ObjectDisposedException or SocketException
+ && Volatile.Read(ref _acceptState) == Abandoned;
+
+ private async Task CancelPendingAcceptAsync()
+ {
+ try
+ {
+ await _acceptCts.CancelAsync().ConfigureAwait(false);
+ }
+ catch
+ {
+ // Already cancelled or disposed; nothing left to unblock.
+ }
+ }
+
+ private static bool AreIpAddressesEqual(string ip1, string ip2)
+ {
+ if (ip1 == ip2)
+ {
+ return true;
+ }
+
+ if (!IPAddress.TryParse(ip1, out var addr1) || !IPAddress.TryParse(ip2, out var addr2))
+ {
+ return false;
+ }
+
+ // Normalise IPv4-mapped IPv6 addresses so 127.0.0.1 matches ::ffff:127.0.0.1.
+ return addr1.Equals(addr2) || addr1.MapToIPv6().Equals(addr2.MapToIPv6());
+ }
+}
diff --git a/FmiSrl.FtpServer.Server/Infrastructure/PassivePortLease.cs b/FmiSrl.FtpServer.Server/Infrastructure/PassivePortLease.cs
new file mode 100644
index 0000000..32a2f38
--- /dev/null
+++ b/FmiSrl.FtpServer.Server/Infrastructure/PassivePortLease.cs
@@ -0,0 +1,59 @@
+using System.Net.Sockets;
+
+namespace FmiSrl.FtpServer.Server.Infrastructure;
+
+///
+/// Owns a started together with the passive port it occupies, and gives
+/// that port back to the it came from once disposed.
+///
+///
+/// Tying the port's reservation to the listener's lifetime is what keeps the range from draining:
+/// there is exactly one place that releases a port, and it runs whether the data transfer
+/// succeeded, failed, or was never started at all. Disposing more than once is safe.
+///
+public sealed class PassivePortLease : IDisposable
+{
+ private readonly PassivePortPool? _pool;
+ private int _disposed;
+
+ internal PassivePortLease(PassivePortPool? pool, TcpListener listener, int port)
+ {
+ _pool = pool;
+ Listener = listener;
+ Port = port;
+ }
+
+ ///
+ /// Gets the started listener accepting the client's data connection.
+ ///
+ /// The bound . Do not stop or dispose it directly; dispose the lease instead.
+ public TcpListener Listener { get; }
+
+ ///
+ /// Gets the port the listener is bound to, as advertised to the client in the 227 reply.
+ ///
+ /// The local port as an .
+ public int Port { get; }
+
+ ///
+ /// Stops the listener and returns the port to the pool it was leased from.
+ ///
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) == 1)
+ {
+ return;
+ }
+
+ try
+ {
+ Listener.Dispose();
+ }
+ catch (SocketException)
+ {
+ // The socket is already unusable; the port is released either way.
+ }
+
+ _pool?.ReleasePort(Port);
+ }
+}
diff --git a/FmiSrl.FtpServer.Server/Infrastructure/PassivePortPool.cs b/FmiSrl.FtpServer.Server/Infrastructure/PassivePortPool.cs
new file mode 100644
index 0000000..9878e17
--- /dev/null
+++ b/FmiSrl.FtpServer.Server/Infrastructure/PassivePortPool.cs
@@ -0,0 +1,240 @@
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using Microsoft.Extensions.Logging;
+
+namespace FmiSrl.FtpServer.Server.Infrastructure;
+
+///
+/// Hands out TCP listeners bound to the server's passive port range, and keeps track of which
+/// ports are still in use so that two concurrent data connections are never given the same port.
+///
+///
+/// A single instance is meant to be shared by every session of one server; that shared bookkeeping
+/// is what makes the range safe to use under concurrency.
+///
+/// Ports are handed out round-robin rather than lowest-first. A port that was just released is
+/// therefore the last one to be tried again, which gives the operating system time to drain the
+/// previous connection's TIME_WAIT state. Without that rotation a busy server keeps
+/// retrying the same low port and reports the whole range as exhausted.
+///
+///
+/// When every port in the range is taken the pool falls back to an operating-system assigned
+/// ephemeral port and logs a warning. That keeps transfers working, but the port will usually sit
+/// outside whatever range the firewall was configured for, so the warning is worth alerting on.
+///
+///
+public sealed class PassivePortPool
+{
+ private readonly IPAddress _bindAddress;
+ private readonly int _minPort;
+ private readonly int _maxPort;
+ private readonly ILogger? _logger;
+ private readonly HashSet _leasedPorts = [];
+ private readonly Lock _gate = new();
+ private int _rotationOffset;
+
+ ///
+ /// Creates a pool that binds passive listeners on within the
+ /// inclusive range ...
+ ///
+ /// The local to bind data listeners to, typically .
+ ///
+ /// The lowest port of the passive range, inclusive. Pass 0 to configure no range at all,
+ /// in which case every listener is bound to an operating-system assigned ephemeral port.
+ ///
+ /// The highest port of the passive range, inclusive. Must not be lower than .
+ /// An optional used to warn when the range is exhausted.
+ /// A port is outside 0..65535, or is greater than .
+ public PassivePortPool(
+ IPAddress bindAddress,
+ int minPort,
+ int maxPort,
+ ILogger? logger = null)
+ {
+ ArgumentNullException.ThrowIfNull(bindAddress);
+ ArgumentOutOfRangeException.ThrowIfNegative(minPort);
+ ArgumentOutOfRangeException.ThrowIfGreaterThan(maxPort, 65535);
+ ArgumentOutOfRangeException.ThrowIfGreaterThan(minPort, maxPort);
+
+ _bindAddress = bindAddress;
+ _minPort = minPort;
+ _maxPort = maxPort;
+ _logger = logger;
+ }
+
+ ///
+ /// Creates a pool from the server's .
+ ///
+ /// The supplying the listening address and passive port range.
+ /// An optional used to warn when the range is exhausted.
+ public PassivePortPool(FtpServerConfigurationOptions configuration, ILogger? logger = null)
+ : this(
+ ParseBindAddress(configuration),
+ configuration.PasvMinPort,
+ configuration.PasvMaxPort,
+ logger)
+ {
+ }
+
+ ///
+ /// Binds a listener on a free port and reserves that port until the lease is disposed.
+ ///
+ ///
+ /// A owning the started listener. Disposing it stops the
+ /// listener and returns the port to this pool.
+ ///
+ /// No port could be bound, not even an ephemeral one.
+ public PassivePortLease Bind()
+ {
+ if (!HasConfiguredRange)
+ {
+ return LeaseEphemeralPort();
+ }
+
+ var portsWithForeignListeners = GetPortsWithActiveListeners();
+
+ foreach (var port in CandidatePortsInRotation())
+ {
+ var lease = TryLease(port, portsWithForeignListeners);
+ if (lease is not null)
+ {
+ return lease;
+ }
+ }
+
+ return LeaseEphemeralPortAfterExhaustion();
+ }
+
+ private bool HasConfiguredRange => _minPort > 0;
+
+ internal void ReleasePort(int port)
+ {
+ lock (_gate)
+ {
+ _leasedPorts.Remove(port);
+ }
+ }
+
+ private PassivePortLease? TryLease(int port, HashSet portsWithForeignListeners)
+ {
+ if (portsWithForeignListeners.Contains(port) || !TryReservePort(port))
+ {
+ return null;
+ }
+
+ var listener = TryBindListener(port);
+ if (listener is null)
+ {
+ ReleasePort(port);
+ return null;
+ }
+
+ return new PassivePortLease(this, listener, port);
+ }
+
+ private bool TryReservePort(int port)
+ {
+ lock (_gate)
+ {
+ return _leasedPorts.Add(port);
+ }
+ }
+
+ private IEnumerable CandidatePortsInRotation()
+ {
+ var portCount = _maxPort - _minPort + 1;
+ var start = NextRotationOffset(portCount);
+
+ for (var offset = 0; offset < portCount; offset++)
+ {
+ yield return _minPort + (start + offset) % portCount;
+ }
+ }
+
+ private int NextRotationOffset(int portCount)
+ {
+ lock (_gate)
+ {
+ var offset = _rotationOffset;
+ _rotationOffset = (_rotationOffset + 1) % portCount;
+ return offset;
+ }
+ }
+
+ private PassivePortLease LeaseEphemeralPortAfterExhaustion()
+ {
+ var lease = LeaseEphemeralPort();
+
+ _logger?.LogWarning(
+ "Passive port range {MinPort}-{MaxPort} is exhausted; fell back to ephemeral port {Port}, " +
+ "which is likely to be blocked by any firewall rule scoped to the configured range",
+ _minPort, _maxPort, lease.Port);
+
+ return lease;
+ }
+
+ private PassivePortLease LeaseEphemeralPort()
+ {
+ var listener = CreateListener(0);
+ listener.Start();
+ var port = ((IPEndPoint)listener.LocalEndpoint).Port;
+
+ return new PassivePortLease(pool: null, listener, port);
+ }
+
+ private TcpListener? TryBindListener(int port)
+ {
+ var listener = CreateListener(port);
+ try
+ {
+ listener.Start();
+ return listener;
+ }
+ catch (SocketException)
+ {
+ listener.Dispose();
+ return null;
+ }
+ }
+
+ private TcpListener CreateListener(int port)
+ {
+ var listener = new TcpListener(_bindAddress, port);
+ if (ShouldReuseTimeWaitPorts)
+ {
+ listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
+ }
+
+ return listener;
+ }
+
+ ///
+ /// Every completed download leaves its passive port in TIME_WAIT, because the server is
+ /// the side that closes the data connection. On Linux and macOS a fresh listener cannot bind
+ /// such a port without SO_REUSEADDR, which would cap a range at roughly one transfer per
+ /// port per TIME_WAIT interval; there the flag only relaxes TIME_WAIT and cannot
+ /// displace a live listener, so it is safe to set. Windows needs no flag — a listener binds
+ /// over TIME_WAIT connections already — and there SO_REUSEADDR would additionally
+ /// let another process bind over a port we own, so it is deliberately left off.
+ ///
+ private static bool ShouldReuseTimeWaitPorts => !OperatingSystem.IsWindows();
+
+ ///
+ /// On Windows a listener bound to a specific IP (for example 127.0.0.1:50000) shadows a
+ /// wildcard listener (0.0.0.0:50000) for traffic to that IP: our Start() succeeds but
+ /// the client's connection is delivered to the more specific socket. Skipping every port that
+ /// already has a listener on any address avoids silently binding a port we would never be
+ /// handed connections on. It also stops SO_REUSEADDR from letting us bind on top of a
+ /// listener that another process legitimately owns.
+ ///
+ private static HashSet GetPortsWithActiveListeners() =>
+ [
+ .. IPGlobalProperties.GetIPGlobalProperties()
+ .GetActiveTcpListeners()
+ .Select(endPoint => endPoint.Port)
+ ];
+
+ private static IPAddress ParseBindAddress(FtpServerConfigurationOptions configuration) =>
+ IPAddress.TryParse(configuration.ListeningIp, out var address) ? address : IPAddress.Any;
+}
diff --git a/FmiSrl.FtpServer.Tests.Integration/PassivePortExhaustionTests.cs b/FmiSrl.FtpServer.Tests.Integration/PassivePortExhaustionTests.cs
new file mode 100644
index 0000000..7c088c6
--- /dev/null
+++ b/FmiSrl.FtpServer.Tests.Integration/PassivePortExhaustionTests.cs
@@ -0,0 +1,244 @@
+using System.Net.NetworkInformation;
+using FluentFTP;
+using FmiSrl.FtpServer.Server;
+using FmiSrl.FtpServer.Server.Abstractions;
+using FmiSrl.FtpServer.Server.Services;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+
+namespace FmiSrl.FtpServer.Tests.Integration;
+
+public class PassivePortExhaustionTests : IAsyncDisposable
+{
+ private const int PassivePortCount = 3;
+ private const int TransferCount = 8;
+ private static readonly TimeSpan IdleTimeout = TimeSpan.FromSeconds(1);
+ private static int _nextControlPort = 2200;
+ private static int _nextPassivePort = 20000;
+
+ private readonly Server.FtpServer _server;
+ private readonly RecordingLogger _logger = new();
+ private readonly string _rootPath;
+ private readonly string _userRoot;
+ private readonly int _controlPort;
+ private readonly int _minPassivePort;
+ private readonly int _maxPassivePort;
+
+ public PassivePortExhaustionTests()
+ {
+ _controlPort = Interlocked.Increment(ref _nextControlPort);
+ _rootPath = Path.Combine(Path.GetTempPath(), "FtpPasvTests_" + Guid.NewGuid().ToString("N"));
+ _userRoot = Path.Combine(_rootPath, "test");
+ Directory.CreateDirectory(_userRoot);
+
+ (_minPassivePort, _maxPassivePort) = FindFreePortRange(PassivePortCount);
+
+ var fileSystem = new PhysicalFileSystemProvider(
+ Options.Create(new PhysicalFileSystemProviderOptions { RootDirectory = _rootPath }));
+
+ var authenticator = new SimpleAuthenticationProvider(
+ Options.Create(new SimpleAuthenticationProviderOptions { Username = "test", Password = "password" }));
+
+ var serverOptions = Options.Create(new FtpServerConfigurationOptions
+ {
+ ListeningIp = "127.0.0.1",
+ FtpPort = _controlPort,
+ PasvMinPort = _minPassivePort,
+ PasvMaxPort = _maxPassivePort,
+ PasvIdleTimeout = IdleTimeout,
+ ServerName = "PasvTestServer"
+ });
+
+ _server = new Server.FtpServer(
+ fileSystem,
+ authenticator,
+ Enumerable.Empty(),
+ Enumerable.Empty(),
+ serverOptions,
+ _logger);
+ }
+
+ [Fact]
+ public async Task When_more_transfers_run_than_the_range_has_ports_should_keep_reusing_the_range()
+ {
+ //Arrange
+ const string content = "passive port reuse";
+ await File.WriteAllTextAsync(Path.Combine(_userRoot, "sample.txt"), content);
+ await _server.StartAsync();
+ using var client = new AsyncFtpClient("127.0.0.1", "test", "password", _controlPort);
+ await client.Connect();
+
+ //Act
+ for (var transfer = 0; transfer < TransferCount; transfer++)
+ {
+ var downloaded = await client.DownloadBytes("/sample.txt", CancellationToken.None);
+ Assert.Equal(content, System.Text.Encoding.UTF8.GetString(downloaded!));
+ }
+
+ //Assert
+ Assert.DoesNotContain(_logger.Warnings, warning => warning.Contains("exhausted", StringComparison.OrdinalIgnoreCase));
+ }
+
+ [Fact]
+ public async Task When_a_client_issues_pasv_without_transferring_should_release_the_port_on_disconnect()
+ {
+ //Arrange
+ await _server.StartAsync();
+ var client = new AsyncFtpClient("127.0.0.1", "test", "password", _controlPort);
+ await client.Connect();
+
+ //Act
+ for (var attempt = 0; attempt < PassivePortCount * 2; attempt++)
+ {
+ await client.Execute("PASV");
+ }
+
+ await client.Disconnect();
+ client.Dispose();
+
+ //Assert
+ Assert.DoesNotContain(_logger.Warnings, warning => warning.Contains("exhausted", StringComparison.OrdinalIgnoreCase));
+ }
+
+ ///
+ /// Clients that ask for a passive port and then never dial in are what actually drains the
+ /// range in production: an aborted transfer or a dropped network leaves the session idle but
+ /// still holding its port. Here every port in the range is pinned that way at once, so the
+ /// last client can only be served from the range if the abandoned ports were reclaimed.
+ ///
+ [Fact]
+ public async Task When_every_port_is_pinned_by_idle_sessions_should_reclaim_them_for_the_next_client()
+ {
+ //Arrange
+ await _server.StartAsync();
+ var idleClients = new List();
+
+ foreach (var _ in Enumerable.Range(0, PassivePortCount))
+ {
+ var idleClient = new AsyncFtpClient("127.0.0.1", "test", "password", _controlPort);
+ await idleClient.Connect();
+ await idleClient.Execute("PASV");
+ idleClients.Add(idleClient);
+ }
+
+ //Act
+ await Task.Delay(IdleTimeout * 3);
+
+ using var lateClient = new AsyncFtpClient("127.0.0.1", "test", "password", _controlPort);
+ await lateClient.Connect();
+ var reply = await lateClient.Execute("PASV");
+
+ //Assert
+ try
+ {
+ Assert.True(reply.Success, reply.ErrorMessage);
+ Assert.InRange(ParseAdvertisedPort(reply.Message), _minPassivePort, _maxPassivePort);
+ Assert.DoesNotContain(_logger.Warnings, warning => warning.Contains("exhausted", StringComparison.OrdinalIgnoreCase));
+ }
+ finally
+ {
+ foreach (var idleClient in idleClients)
+ {
+ idleClient.Dispose();
+ }
+ }
+ }
+
+ ///
+ /// Reads the port out of a 227 reply of the form "Entering Passive Mode (h1,h2,h3,h4,p1,p2).".
+ ///
+ private static int ParseAdvertisedPort(string reply)
+ {
+ var start = reply.IndexOf('(');
+ var end = reply.IndexOf(')');
+ Assert.InRange(start, 0, int.MaxValue);
+ Assert.InRange(end, start, int.MaxValue);
+
+ var parts = reply[(start + 1)..end].Split(',');
+ Assert.Equal(6, parts.Length);
+
+ return int.Parse(parts[4]) * 256 + int.Parse(parts[5]);
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ await _server.StopAsync();
+
+ try
+ {
+ Directory.Delete(_rootPath, true);
+ }
+ catch
+ {
+ // Ignore cleanup errors in tests
+ }
+
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Stays below Windows' default dynamic port range (49152-65535) so that ports the operating
+ /// system hands out to client sockets never collide with the range under test, and advances a
+ /// shared cursor so tests running in parallel get disjoint ranges.
+ ///
+ private static (int MinPort, int MaxPort) FindFreePortRange(int portCount)
+ {
+ var portsInUse = IPGlobalProperties.GetIPGlobalProperties()
+ .GetActiveTcpListeners()
+ .Select(endPoint => endPoint.Port)
+ .ToHashSet();
+
+ while (true)
+ {
+ var start = Interlocked.Add(ref _nextPassivePort, portCount) - portCount;
+ if (start > 20900 - portCount)
+ {
+ throw new InvalidOperationException($"No free range of {portCount} ports is available for this test.");
+ }
+
+ if (Enumerable.Range(start, portCount).All(port => !portsInUse.Contains(port)))
+ {
+ return (start, start + portCount - 1);
+ }
+ }
+ }
+
+ private sealed class RecordingLogger : ILogger
+ {
+ private readonly List _warnings = [];
+ private readonly Lock _gate = new();
+
+ public IReadOnlyList Warnings
+ {
+ get
+ {
+ lock (_gate)
+ {
+ return [.. _warnings];
+ }
+ }
+ }
+
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;
+
+ public void Log(
+ LogLevel logLevel,
+ EventId eventId,
+ TState state,
+ Exception? exception,
+ Func formatter)
+ {
+ if (logLevel < LogLevel.Warning)
+ {
+ return;
+ }
+
+ lock (_gate)
+ {
+ _warnings.Add(formatter(state, exception));
+ }
+ }
+ }
+}
diff --git a/FmiSrl.FtpServer.Tests.Unit/Infrastructure/PassiveDataConnectionTests.cs b/FmiSrl.FtpServer.Tests.Unit/Infrastructure/PassiveDataConnectionTests.cs
new file mode 100644
index 0000000..3ebebef
--- /dev/null
+++ b/FmiSrl.FtpServer.Tests.Unit/Infrastructure/PassiveDataConnectionTests.cs
@@ -0,0 +1,111 @@
+using System.Net;
+using System.Net.Sockets;
+using FmiSrl.FtpServer.Server.Infrastructure;
+
+namespace FmiSrl.FtpServer.Tests.Unit.Infrastructure;
+
+public class PassiveDataConnectionTests
+{
+ private static readonly TimeSpan ShortIdleTimeout = TimeSpan.FromMilliseconds(200);
+ private static readonly TimeSpan GenerousIdleTimeout = TimeSpan.FromSeconds(10);
+
+ [Fact]
+ public async Task When_no_client_connects_within_the_idle_timeout_should_return_the_port_to_the_pool()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(1);
+ var pool = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ await using var sut = new PassiveDataConnection(pool.Bind(), "127.0.0.1", ShortIdleTimeout);
+ var abandonedPort = sut.Port;
+
+ //Act
+ await WaitForPortReleaseAsync();
+
+ //Assert
+ using var reused = pool.Bind();
+ Assert.Equal(abandonedPort, reused.Port);
+ }
+
+ [Fact]
+ public async Task When_the_idle_timeout_elapses_should_fail_the_pending_accept_with_a_timeout()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(1);
+ var pool = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ await using var sut = new PassiveDataConnection(pool.Bind(), "127.0.0.1", ShortIdleTimeout);
+
+ //Act & Assert
+ await Assert.ThrowsAsync(() => sut.GetStreamAsync());
+ }
+
+ [Fact]
+ public async Task When_an_authorized_client_connects_should_expose_the_data_stream()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(1);
+ var pool = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ await using var sut = new PassiveDataConnection(pool.Bind(), "127.0.0.1", GenerousIdleTimeout);
+ using var client = new TcpClient();
+ await client.ConnectAsync(IPAddress.Loopback, sut.Port);
+
+ //Act
+ var stream = await sut.GetStreamAsync();
+
+ //Assert
+ Assert.True(stream.CanWrite);
+ }
+
+ [Fact]
+ public async Task When_a_client_connects_before_the_timeout_should_keep_the_transfer_alive_afterwards()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(1);
+ var pool = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ await using var sut = new PassiveDataConnection(pool.Bind(), "127.0.0.1", ShortIdleTimeout);
+ using var client = new TcpClient();
+ await client.ConnectAsync(IPAddress.Loopback, sut.Port);
+ var stream = await sut.GetStreamAsync();
+
+ //Act
+ await WaitForPortReleaseAsync();
+ await stream.WriteAsync("ping"u8.ToArray());
+
+ //Assert
+ var received = new byte[4];
+ await client.GetStream().ReadExactlyAsync(received);
+ Assert.Equal("ping"u8.ToArray(), received);
+ }
+
+ [Fact]
+ public async Task When_an_unauthorized_client_connects_should_reject_the_data_connection()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(1);
+ var pool = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ await using var sut = new PassiveDataConnection(pool.Bind(), "10.11.12.13", GenerousIdleTimeout);
+ using var client = new TcpClient();
+ await client.ConnectAsync(IPAddress.Loopback, sut.Port);
+
+ //Act & Assert
+ await Assert.ThrowsAsync(() => sut.GetStreamAsync());
+ }
+
+ [Fact]
+ public async Task When_disposed_should_return_the_port_to_the_pool()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(1);
+ var pool = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ var sut = new PassiveDataConnection(pool.Bind(), "127.0.0.1", GenerousIdleTimeout);
+
+ //Act
+ await sut.DisposeAsync();
+ await sut.DisposeAsync();
+
+ //Assert
+ using var reused = pool.Bind();
+ Assert.Equal(minPort, reused.Port);
+ }
+
+ private static Task WaitForPortReleaseAsync() => Task.Delay(ShortIdleTimeout * 5);
+}
diff --git a/FmiSrl.FtpServer.Tests.Unit/Infrastructure/PassivePortPoolTests.cs b/FmiSrl.FtpServer.Tests.Unit/Infrastructure/PassivePortPoolTests.cs
new file mode 100644
index 0000000..9ade70f
--- /dev/null
+++ b/FmiSrl.FtpServer.Tests.Unit/Infrastructure/PassivePortPoolTests.cs
@@ -0,0 +1,167 @@
+using System.Net;
+using System.Net.NetworkInformation;
+using FmiSrl.FtpServer.Server.Infrastructure;
+
+namespace FmiSrl.FtpServer.Tests.Unit.Infrastructure;
+
+public class PassivePortPoolTests
+{
+ [Fact]
+ public void When_several_ports_are_leased_at_once_should_never_hand_out_the_same_port_twice()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(3);
+ var sut = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+
+ //Act
+ var leases = Enumerable.Range(0, 3).Select(_ => sut.Bind()).ToList();
+
+ //Assert
+ try
+ {
+ Assert.Equal(3, leases.Select(lease => lease.Port).Distinct().Count());
+ Assert.All(leases, lease => Assert.InRange(lease.Port, minPort, maxPort));
+ }
+ finally
+ {
+ leases.ForEach(lease => lease.Dispose());
+ }
+ }
+
+ [Fact]
+ public void When_the_range_is_fully_leased_should_fall_back_to_an_ephemeral_port()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(2);
+ var sut = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ using var first = sut.Bind();
+ using var second = sut.Bind();
+
+ //Act
+ using var overflow = sut.Bind();
+
+ //Assert
+ Assert.NotInRange(overflow.Port, minPort, maxPort);
+ }
+
+ [Fact]
+ public void When_a_lease_is_disposed_should_return_its_port_to_the_range()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(2);
+ var sut = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ sut.Bind().Dispose();
+ sut.Bind().Dispose();
+
+ //Act
+ using var first = sut.Bind();
+ using var second = sut.Bind();
+
+ //Assert
+ Assert.InRange(first.Port, minPort, maxPort);
+ Assert.InRange(second.Port, minPort, maxPort);
+ }
+
+ [Fact]
+ public void When_a_port_was_just_released_should_prefer_a_different_port_for_the_next_lease()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(2);
+ var sut = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ int releasedPort;
+ using (var first = sut.Bind())
+ {
+ releasedPort = first.Port;
+ }
+
+ //Act
+ using var second = sut.Bind();
+
+ //Assert
+ Assert.NotEqual(releasedPort, second.Port);
+ }
+
+ [Fact]
+ public void When_a_lease_is_disposed_twice_should_release_its_port_only_once()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(1);
+ var sut = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+ var lease = sut.Bind();
+ lease.Dispose();
+ lease.Dispose();
+
+ //Act
+ using var reused = sut.Bind();
+ using var overflow = sut.Bind();
+
+ //Assert
+ Assert.Equal(minPort, reused.Port);
+ Assert.NotInRange(overflow.Port, minPort, maxPort);
+ }
+
+ [Fact]
+ public void When_a_port_in_the_range_already_has_a_listener_should_skip_it()
+ {
+ //Arrange
+ var (minPort, maxPort) = FreePortRange.Find(2);
+ var occupyingPool = new PassivePortPool(IPAddress.Loopback, minPort, minPort);
+ using var occupied = occupyingPool.Bind();
+ var sut = new PassivePortPool(IPAddress.Loopback, minPort, maxPort);
+
+ //Act
+ using var lease = sut.Bind();
+
+ //Assert
+ Assert.NotEqual(occupied.Port, lease.Port);
+ }
+
+ [Fact]
+ public void When_the_minimum_port_is_above_the_maximum_should_reject_the_range()
+ {
+ //Act & Assert
+ Assert.Throws(
+ () => new PassivePortPool(IPAddress.Loopback, 50100, 50000));
+ }
+}
+
+///
+/// The cursor only ever moves forward, so two test classes running in parallel are never handed
+/// overlapping ranges. Without that, one class binding a port another class expected to be free
+/// makes the pool fall back to an ephemeral port and the assertions fail for reasons that have
+/// nothing to do with the code under test.
+///
+/// The search deliberately stays below Windows' default dynamic port range (49152-65535). Ports
+/// handed out there by the operating system — to client sockets, and to the pool's own
+/// ephemeral fallback — would otherwise land on a range a parallel test had already picked.
+///
+///
+internal static class FreePortRange
+{
+ private const int LowestSearchPort = 21000;
+ private const int HighestSearchPort = 30000;
+
+ private static int _searchCursor = LowestSearchPort;
+
+ internal static (int MinPort, int MaxPort) Find(int portCount)
+ {
+ var portsInUse = IPGlobalProperties.GetIPGlobalProperties()
+ .GetActiveTcpListeners()
+ .Select(endPoint => endPoint.Port)
+ .ToHashSet();
+
+ while (true)
+ {
+ var start = Interlocked.Add(ref _searchCursor, portCount) - portCount;
+ if (start > HighestSearchPort - portCount)
+ {
+ throw new InvalidOperationException($"No free range of {portCount} ports is available for this test.");
+ }
+
+ if (Enumerable.Range(start, portCount).All(port => !portsInUse.Contains(port)))
+ {
+ return (start, start + portCount - 1);
+ }
+ }
+ }
+}
diff --git a/FmiSrl.FtpServer.slnx b/FmiSrl.FtpServer.slnx
index 48ffd47..87a7346 100644
--- a/FmiSrl.FtpServer.slnx
+++ b/FmiSrl.FtpServer.slnx
@@ -1,6 +1,7 @@
-
-
-
-
+
+
+
+
+
diff --git a/Miku.Core/.AssemblyAttributes b/Miku.Core/.AssemblyAttributes
new file mode 100644
index 0000000..348b87f
--- /dev/null
+++ b/Miku.Core/.AssemblyAttributes
@@ -0,0 +1,4 @@
+//
+using System;
+using System.Reflection;
+[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
diff --git a/Miku.Core/INetMiddleware.cs b/Miku.Core/INetMiddleware.cs
new file mode 100644
index 0000000..638283a
--- /dev/null
+++ b/Miku.Core/INetMiddleware.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Buffers;
+
+namespace Miku.Core
+{
+ ///
+ /// Middleware for processing data before sending or receiving
+ ///
+ public interface INetMiddleware
+ {
+ ///
+ /// Process data before sending
+ ///
+ /// Source data to be processed
+ /// Destination buffer to write processed data to
+ void ProcessSend(ReadOnlyMemory src, ArrayBufferWriter dst);
+
+ ///
+ /// Process data after receiving
+ ///
+ /// Source data to be processed
+ /// Destination buffer to write processed data to
+ /// Whether to halt the processing and how many bytes are consumed from the original input
+ (bool halt, int consumedFromOrigin) ProcessReceive(ReadOnlyMemory src, ArrayBufferWriter dst);
+ }
+}
\ No newline at end of file
diff --git a/Miku.Core/Miku.Core.csproj b/Miku.Core/Miku.Core.csproj
new file mode 100644
index 0000000..04a1fed
--- /dev/null
+++ b/Miku.Core/Miku.Core.csproj
@@ -0,0 +1,53 @@
+
+
+
+ disable
+ enable
+ 14
+ false
+ 2.0.0
+ Miku
+ Miku
+ JasonXuDeveloper
+ High performance TCP server/client library written in C#
+ JasonXuDeveloper
+ https://github.com/JasonXuDeveloper/Miku
+ https://github.com/JasonXuDeveloper/Miku
+ git
+ TCP;Networking;High-Perofrmance
+ MIT
+ README.md
+ true
+ refs/heads/main
+ true
+ true
+ true
+ embedded
+ net10.0
+
+
+
+
+ $([System.IO.Path]::Combine('$(IntermediateOutputPath)','$(TargetFrameworkMoniker).AssemblyAttributes$(DefaultLanguageSourceExtension)'))
+
+
+
+
+
+
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Miku.Core/MultiMemory.cs b/Miku.Core/MultiMemory.cs
new file mode 100644
index 0000000..a153d22
--- /dev/null
+++ b/Miku.Core/MultiMemory.cs
@@ -0,0 +1,26 @@
+using System;
+
+public readonly struct MultiMemory
+{
+ public readonly Memory First;
+ public readonly Memory Second;
+
+ public MultiMemory(Memory first, Memory second)
+ {
+ First = first;
+ Second = second;
+ }
+
+ public static MultiMemory Empty => new(Memory.Empty, Memory.Empty);
+ public bool IsEmpty => First.IsEmpty && Second.IsEmpty;
+ public int Length => First.Length + Second.Length;
+
+ public void CopyTo(Span span)
+ {
+ if (span.Length < Length)
+ throw new ArgumentException("Span is too small to copy the data.");
+
+ First.Span.CopyTo(span);
+ Second.Span.CopyTo(span.Slice(First.Length));
+ }
+}
\ No newline at end of file
diff --git a/Miku.Core/NetBuffer.cs b/Miku.Core/NetBuffer.cs
new file mode 100644
index 0000000..9758692
--- /dev/null
+++ b/Miku.Core/NetBuffer.cs
@@ -0,0 +1,190 @@
+using System;
+using System.Buffers;
+using System.Threading;
+
+public class NetBuffer : IDisposable
+{
+ private readonly byte[] _buffer;
+ private int _head; // next write position (producer)
+ private int _tail; // next read position (consumer)
+ private bool _disposed;
+
+ public event Action OnWarning;
+
+ public NetBuffer(int capacity = 8192)
+ {
+ if (capacity < 2) throw new ArgumentOutOfRangeException(nameof(capacity));
+ _buffer = ArrayPool.Shared.Rent(capacity);
+ _head = 0;
+ _tail = 0;
+ }
+
+ // How many bytes are available to read.
+ public int Length
+ {
+ get
+ {
+ int head = Volatile.Read(ref _head);
+ int tail = Volatile.Read(ref _tail);
+ return head >= tail
+ ? head - tail
+ : head + _buffer.Length - tail;
+ }
+ }
+
+ // How many bytes we can write without overwriting unread data.
+ public int FreeSpace
+ {
+ get
+ {
+ int head = Volatile.Read(ref _head);
+ int tail = Volatile.Read(ref _tail);
+ // leave one slot empty so head==tail always means "empty"
+ return tail > head
+ ? tail - head - 1
+ : tail + _buffer.Length - head - 1;
+ }
+ }
+
+ // Total capacity of the buffer
+ public int Capacity => _buffer.Length;
+
+ public void Clear()
+ {
+ if (_disposed) throw new ObjectDisposedException(nameof(NetBuffer));
+ Volatile.Write(ref _head, 0);
+ Volatile.Write(ref _tail, 0);
+ }
+
+ public void Dispose()
+ {
+ if (_disposed) return;
+ ArrayPool.Shared.Return(_buffer);
+ _disposed = true;
+ }
+
+ // --- PRODUCER SIDE (only one thread may call these) ---
+
+ public MultiMemory GetWriteSegments()
+ {
+ if (_disposed)
+ return MultiMemory.Empty;
+
+ int head = Volatile.Read(ref _head);
+ int free = FreeSpace;
+ if (free == 0)
+ return MultiMemory.Empty;
+
+ // can write up to end of array, then wrap
+ int firstLen = Math.Min(free, _buffer.Length - head);
+ int secondLen = free - firstLen;
+
+ var first = new Memory(_buffer, head, firstLen);
+ var second = secondLen > 0
+ ? new Memory(_buffer, 0, secondLen)
+ : Memory.Empty;
+
+ return new MultiMemory(first, second);
+ }
+
+ ///
+ /// Get write segments as ArraySegment for direct SAEA BufferList usage
+ /// This avoids MemoryMarshal overhead and provides zero-alloc access
+ ///
+ public (ArraySegment First, ArraySegment Second) GetWriteSegmentsAsArraySegments()
+ {
+ if (_disposed)
+ return (ArraySegment.Empty, ArraySegment.Empty);
+
+ int head = Volatile.Read(ref _head);
+ int free = FreeSpace;
+ if (free == 0)
+ return (ArraySegment.Empty, ArraySegment.Empty);
+
+ // can write up to end of array, then wrap
+ int firstLen = Math.Min(free, _buffer.Length - head);
+ int secondLen = free - firstLen;
+
+ var first = new ArraySegment(_buffer, head, firstLen);
+ var second = secondLen > 0
+ ? new ArraySegment(_buffer, 0, secondLen)
+ : ArraySegment.Empty;
+
+ return (first, second);
+ }
+
+ public void AdvanceWrite(int count)
+ {
+ if (_disposed) throw new ObjectDisposedException(nameof(NetBuffer));
+ if (count < 0)
+ throw new ArgumentOutOfRangeException(nameof(count), "Count cannot be negative");
+
+ int free = FreeSpace;
+
+ // overwrite old data?
+ if (count > free)
+ {
+ OnWarning?.Invoke(
+ $"Buffer full: dropping entire incoming chunk of {count} bytes.");
+ return;
+ }
+
+ // advance head
+ int head = Volatile.Read(ref _head);
+ int newHead = head + count;
+ if (newHead >= _buffer.Length) newHead -= _buffer.Length;
+ Volatile.Write(ref _head, newHead);
+ }
+
+ // --- CONSUMER SIDE (only one thread may call these) ---
+
+ public MultiMemory GetReadSegments()
+ {
+ if (_disposed)
+ return MultiMemory.Empty;
+
+ int head = Volatile.Read(ref _head);
+ int tail = Volatile.Read(ref _tail);
+ int len = head >= tail
+ ? head - tail
+ : head + _buffer.Length - tail;
+
+ if (len == 0)
+ return MultiMemory.Empty;
+
+ int firstLen = Math.Min(len, _buffer.Length - tail);
+ int secondLen = len - firstLen;
+
+ var first = new Memory(_buffer, tail, firstLen);
+ var second = secondLen > 0
+ ? new Memory(_buffer, 0, secondLen)
+ : Memory.Empty;
+
+ return new MultiMemory(first, second);
+ }
+
+ public void AdvanceRead(int count)
+ {
+ if (_disposed) throw new ObjectDisposedException(nameof(NetBuffer));
+ if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
+
+ int head = Volatile.Read(ref _head);
+ int tail = Volatile.Read(ref _tail);
+ int len = head >= tail
+ ? head - tail
+ : head + _buffer.Length - tail;
+
+ if (count > len)
+ {
+ OnWarning?.Invoke(
+ $"Requested to read {count}, but only {len} available. Clearing buffer.");
+ // drop all
+ Volatile.Write(ref _tail, head);
+ return;
+ }
+
+ int newTail = tail + count;
+ if (newTail >= _buffer.Length) newTail -= _buffer.Length;
+ Volatile.Write(ref _tail, newTail);
+ }
+}
\ No newline at end of file
diff --git a/Miku.Core/NetClient.cs b/Miku.Core/NetClient.cs
new file mode 100644
index 0000000..a8b269f
--- /dev/null
+++ b/Miku.Core/NetClient.cs
@@ -0,0 +1,1463 @@
+using System;
+using System.Buffers;
+using System.Threading;
+using System.Net.Sockets;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Collections.Concurrent;
+using System.Threading.Channels;
+using System.Diagnostics;
+
+namespace Miku.Core
+{
+ ///
+ /// Performance statistics for NetClient to track optimization effectiveness
+ ///
+ public struct NetClientStats
+ {
+ public long MessagesReceived;
+ public long MessagesSent;
+ public long BytesReceived;
+ public long BytesSent;
+ public long OutgoingMessagesDropped; // Only outgoing messages can be dropped (channel full)
+ public long ErrorsSkipped; // Errors skipped due to null OnError handler
+ public long TempBufferAllocations; // Temp allocations for segmented data
+
+ ///
+ /// Drop rate for outgoing messages only (incoming messages use direct callbacks - no drops)
+ ///
+ public readonly double OutgoingDropRate =>
+ MessagesSent > 0 ? (double)OutgoingMessagesDropped / (MessagesSent + OutgoingMessagesDropped) : 0;
+
+ public readonly double ErrorSkipRate =>
+ ErrorsSkipped > 0 ? (double)ErrorsSkipped / (ErrorsSkipped + MessagesReceived) : 0;
+
+ ///
+ /// Reset all counters to prevent overflow when approaching long.MaxValue
+ /// Thread-safe via Interlocked.Exchange.
+ ///
+ public void ResetIfNearOverflow()
+ {
+ const long resetThreshold = (long)(long.MaxValue * 0.9);
+
+ if (MessagesReceived > resetThreshold || MessagesSent > resetThreshold ||
+ BytesReceived > resetThreshold || BytesSent > resetThreshold)
+ {
+ Interlocked.Exchange(ref MessagesReceived, 0);
+ Interlocked.Exchange(ref MessagesSent, 0);
+ Interlocked.Exchange(ref BytesReceived, 0);
+ Interlocked.Exchange(ref BytesSent, 0);
+ Interlocked.Exchange(ref OutgoingMessagesDropped, 0);
+ Interlocked.Exchange(ref ErrorsSkipped, 0);
+ Interlocked.Exchange(ref TempBufferAllocations, 0);
+ }
+ }
+ }
+
+ ///
+ /// Raw message data for the outgoing channel with its buffer writer
+ ///
+ internal readonly struct RawMessage
+ {
+ public readonly ArrayBufferWriter BufferWriter;
+ public readonly int Length;
+
+ public RawMessage(ArrayBufferWriter bufferWriter, int length)
+ {
+ BufferWriter = bufferWriter;
+ Length = length;
+ }
+ }
+
+ ///
+ /// Configuration options for NetClient performance tuning
+ ///
+ public class NetClientConfig
+ {
+ ///
+ /// Number of messages to process before yielding thread
+ ///
+ public int YieldThreshold { get; set; } = 5;
+
+ ///
+ /// Number of messages to batch before updating stats
+ ///
+ public int BatchSize { get; set; } = 32;
+
+ ///
+ /// Channel capacity for outgoing messages
+ ///
+ public int OutgoingChannelCapacity { get; set; } = 10000;
+ }
+
+ ///
+ /// A client for connecting to a remote host with channel-based data flow
+ ///
+ public class NetClient : IDisposable
+ {
+ ///
+ /// Shared pool for ArrayBufferWriter instances used across all clients
+ ///
+ private static readonly ConcurrentQueue> BufferPool = new();
+
+ ///
+ /// Default configuration
+ ///
+ private static readonly NetClientConfig DefaultConfig = new();
+
+ ///
+ /// Static counter for generating unique client IDs
+ ///
+ private static int _nextId = 0;
+
+ ///
+ /// Generate next unique client ID with overflow handling
+ ///
+ private static int GetNextId()
+ {
+ int newId;
+ int current;
+ do
+ {
+ current = _nextId;
+ newId = current == int.MaxValue ? 0 : current + 1; // Wrap to 0 on overflow
+ } while (Interlocked.CompareExchange(ref _nextId, newId, current) != current);
+
+ return newId;
+ }
+
+ ///
+ /// Event when the client is connected
+ ///
+ public event Action OnConnected;
+
+ ///
+ /// Event when the client is disconnected
+ ///
+ public event Action OnDisconnected;
+
+ ///
+ /// Event when data is received (called from Dispatch)
+ ///
+ public event Action> OnDataReceived;
+
+ ///
+ /// Event when an error occurred
+ ///
+ public event Action OnError;
+
+ ///
+ /// Unique identifier for the client
+ ///
+ public int Id { get; } = GetNextId();
+
+ ///
+ /// Whether the client is connected
+ ///
+ public bool IsConnected
+ {
+ get
+ {
+ if (_disposed != 0 || !_isConnected) return false;
+
+ try
+ {
+ var socket = _socket; // Capture reference to prevent null reference
+ return socket?.Connected == true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+ }
+
+ ///
+ /// Remote host IP address
+ ///
+ public string Ip { get; private set; }
+
+ public int BufferSize => _bufferSize;
+
+ ///
+ /// Performance statistics for monitoring optimization effectiveness
+ ///
+ public NetClientStats Stats => _stats;
+
+ ///
+ /// Manually reset performance statistics
+ ///
+ public void ResetStats()
+ {
+ _stats = default;
+ }
+
+ private Socket _socket;
+ private bool _isConnected;
+ private int _sending;
+ private volatile int _bufferSize;
+
+ private SocketAsyncEventArgs _receiveArg;
+ private SocketAsyncEventArgs _sendArg;
+ private NetBuffer _receiveBuffer;
+ private readonly List _middlewares = new();
+ private ArrayBufferWriter _currentBufferWriter;
+
+ private readonly ArraySegment[]
+ _saeaBufferList = new ArraySegment[2]; // Fixed-size array to avoid allocations
+
+ private Channel _outgoingChannel;
+
+ private StringBuilder _diagnosticInfoBuilder = new();
+
+ // Pre-allocated exception for performance
+ private static readonly InvalidOperationException CachedReceiveBufferNullException =
+ new("Receive buffer is null");
+
+ // Bounding the pool prevents it from growing indefinitely, which can cause
+ // memory pressure in long-running processes.
+ private const int MaxPooledWriters = 1_024;
+
+ ///
+ /// Get a buffer writer from the pool or create a new one
+ ///
+ private static ArrayBufferWriter GetBufferFromPool() =>
+ BufferPool.TryDequeue(out var writer) ? writer : new ArrayBufferWriter();
+
+ ///
+ /// Return a buffer writer to the pool
+ ///
+ private static void ReturnBufferToPool(ArrayBufferWriter writer)
+ {
+ if (writer == null) return;
+ try
+ {
+#if NET8_0_OR_GREATER
+ writer.ResetWrittenCount();
+#else
+ writer.Clear();
+#endif
+ // ConcurrentQueue.Count is O(N), but this is an acceptable trade-off
+ // for safety, as it's called less frequently than enqueueing.
+ if (BufferPool.Count >= MaxPooledWriters)
+ return;
+
+ BufferPool.Enqueue(writer);
+ }
+ catch
+ {
+ // If returning to the pool fails, let it be garbage collected.
+ }
+ }
+
+ ///
+ /// Resets a buffer writer to be reused.
+ ///
+ private static void ResetBuffer(ArrayBufferWriter writer)
+ {
+#if NET8_0_OR_GREATER
+ writer.ResetWrittenCount();
+#else
+ writer.Clear();
+#endif
+ }
+
+ ///
+ /// Whether there are pending messages to send
+ ///
+ public bool HasPendingSends
+ {
+ get
+ {
+ try
+ {
+ return _outgoingChannel?.Reader.TryPeek(out _) == true;
+ }
+ catch (InvalidOperationException)
+ {
+ // Channel completed
+ return false;
+ }
+ }
+ }
+
+ ///
+ /// Count of pending messages to send
+ ///
+ public int PendingSendCount
+ {
+ get
+ {
+ try
+ {
+ return _outgoingChannel?.Reader.Count ?? 0;
+ }
+ catch (InvalidOperationException)
+ {
+ // Channel completed
+ return 0;
+ }
+ }
+ }
+
+ private int _stopping;
+ private int _inErrorHandler; // To prevent reentrancy in error handling
+ private int _disposed;
+ private bool _isZeroByteReceive;
+
+ // Performance tracking
+ private NetClientStats _stats;
+
+ // Cached values for optimization
+ private int _yieldCounter;
+ private int _overflowCheckCounter;
+ private int _localMessagesReceived;
+ private long _localBytesReceived;
+ private const int OverflowCheckFrequency = 10000;
+
+ ///
+ /// Initialize the client with the given socket and buffer size
+ ///
+ private void InitializeClient(Socket socket, int bufferSize)
+ {
+ _bufferSize = bufferSize;
+ _socket = socket;
+
+ var remoteEndPoint = socket.RemoteEndPoint as System.Net.IPEndPoint;
+ Ip = remoteEndPoint?.Address.ToString() ?? "Unknown";
+
+ _receiveBuffer = new(bufferSize);
+
+ _receiveArg = new SocketAsyncEventArgs();
+ _receiveArg.UserToken = this;
+ _receiveArg.Completed += HandleReadWrite;
+
+ // _saeaBufferList is already allocated as a field.
+ _sendArg = new SocketAsyncEventArgs();
+ _sendArg.UserToken = this;
+ _sendArg.Completed += HandleReadWrite;
+
+ var outgoingOptions = new BoundedChannelOptions(DefaultConfig.OutgoingChannelCapacity)
+ {
+ FullMode = BoundedChannelFullMode.DropWrite, // Drop new messages when the channel is full.
+ SingleReader = true,
+ SingleWriter = false
+ };
+ _outgoingChannel = Channel.CreateBounded(outgoingOptions);
+
+ // Register warning handler after initialization.
+ _receiveBuffer.OnWarning += msg => SafeInvokeOnError(new Exception(msg));
+
+ // Set _isConnected only after all initialization is complete.
+ _isConnected = true;
+
+ OnConnected?.Invoke();
+
+ // Start the first receive.
+ TryStartReceive(_receiveArg);
+ }
+
+ ///
+ /// Initiates an asynchronous receive operation with error handling.
+ ///
+ private void StartReceiveAsync(SocketAsyncEventArgs args)
+ {
+ try
+ {
+ if (!_socket.ReceiveAsync(args))
+ {
+ Receive(args);
+ }
+ }
+ catch (ObjectDisposedException)
+ {
+ // Socket was disposed, so we can ignore this.
+ }
+ catch (Exception e)
+ {
+ SafeInvokeOnError(e);
+ }
+ }
+
+ ///
+ /// Try to start a receive operation, handling buffer space gracefully
+ ///
+ private void TryStartReceive(SocketAsyncEventArgs args)
+ {
+ // Cache state to avoid multiple volatile reads
+ var isDisposed = _disposed != 0;
+ var isConnected = _isConnected;
+ var socket = _socket;
+ var receiveBuffer = _receiveBuffer;
+
+ if (isDisposed || !isConnected || socket == null || receiveBuffer == null)
+ return;
+
+ // Always process existing buffered data first to prevent deadlocks.
+ if (receiveBuffer.Length > 0)
+ {
+ try
+ {
+ ProcessReceivedData();
+ }
+ catch (Exception e)
+ {
+ SafeInvokeOnError(e);
+ }
+ }
+
+ // Re-check state, as it may have changed.
+ if (_disposed != 0 || !_isConnected || _socket == null)
+ return;
+
+ if (SetupReceiveBufferList())
+ {
+ _isZeroByteReceive = false;
+ StartReceiveAsync(args);
+ }
+ else
+ {
+ // Post a zero-byte receive to detect disconnections.
+ _isZeroByteReceive = true;
+ args.BufferList = null;
+ args.SetBuffer(Array.Empty(), 0, 0);
+ StartReceiveAsync(args);
+ }
+ }
+
+ ///
+ /// Setup BufferList for receiving with fixed-size array (zero-alloc)
+ ///
+ /// True if buffer space is available, false if no space
+ private bool SetupReceiveBufferList()
+ {
+ if (_disposed != 0 || !_isConnected || _receiveBuffer == null)
+ return false;
+
+ var (first, second) = _receiveBuffer.GetWriteSegmentsAsArraySegments();
+ if ((first.Count | second.Count) == 0)
+ {
+ return false;
+ }
+
+ // Update fixed-size array in-place to avoid allocations.
+ _saeaBufferList[0] = first;
+ _saeaBufferList[1] = second;
+
+ // Use BufferList for the receive operation.
+ _receiveArg.SetBuffer(null, 0, 0);
+ _receiveArg.BufferList = _saeaBufferList;
+
+ return true;
+ }
+
+ ///
+ /// Cleanup resources on connection failure
+ ///
+ private void CleanupOnConnectionFailure()
+ {
+ _isConnected = false;
+ _bufferSize = 0;
+ _socket?.Close();
+ _socket?.Dispose();
+ _socket = null;
+
+ _receiveBuffer?.Dispose();
+ _receiveBuffer = null;
+
+ _receiveArg?.Dispose();
+ _receiveArg = null;
+
+ _sendArg?.Dispose();
+ _sendArg = null;
+
+ // _saeaBufferList is a field, no need to clear it.
+ _outgoingChannel?.Writer.TryComplete();
+ _outgoingChannel = null;
+ }
+
+ ///
+ /// Safely invoke OnError without causing reentrancy issues
+ ///
+ private void SafeInvokeOnError(Exception exception)
+ {
+ // Prevent reentrancy - if we're already in an error handler, don't invoke again
+ if (Interlocked.CompareExchange(ref _inErrorHandler, 1, 0) == 1)
+ {
+ return;
+ }
+
+ try
+ {
+ OnError?.Invoke(exception);
+ }
+ catch
+ {
+ // Ignore exceptions from error handlers to prevent loops.
+ }
+ finally
+ {
+ Interlocked.Exchange(ref _inErrorHandler, 0);
+ }
+ }
+
+ ///
+ /// Add a middleware to the client
+ ///
+ ///
+ public void AddMiddleware(INetMiddleware middleware)
+ {
+ _middlewares.Add(middleware);
+ }
+
+ ///
+ /// Remove a middleware from the client
+ ///
+ ///
+ public void RemoveMiddleware(INetMiddleware middleware)
+ {
+ _middlewares.Remove(middleware);
+ }
+
+ ///
+ /// Connect to the remote host
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void Connect(string ip, int port, int bufferSize = 1024)
+ {
+ if (_disposed != 0)
+ {
+ throw new ObjectDisposedException(nameof(NetClient));
+ }
+
+ if (_isConnected)
+ {
+ throw new InvalidOperationException("Already connected");
+ }
+
+ if (string.IsNullOrWhiteSpace(ip))
+ {
+ throw new ArgumentException("IP address cannot be null or empty", nameof(ip));
+ }
+
+ if (port <= 0 || port > 65535)
+ {
+ throw new ArgumentException("Port must be between 1 and 65535", nameof(port));
+ }
+
+ // This is important on macOS, where sockets can become invalid after failed connections.
+ if (_socket != null)
+ {
+ try
+ {
+ _socket.Close();
+ _socket.Dispose();
+ }
+ catch
+ {
+ // Ignore cleanup errors.
+ }
+ _socket = null;
+ }
+
+ try
+ {
+ _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
+ _socket.NoDelay = true;
+ _socket.Connect(ip, port);
+
+ InitializeClient(_socket, bufferSize);
+ Ip = ip;
+ }
+ catch (Exception e)
+ {
+ CleanupOnConnectionFailure();
+ SafeInvokeOnError(e);
+ throw;
+ }
+ }
+
+ ///
+ /// When a server accepts a connection, use this method to connect the client
+ ///
+ ///
+ ///
+ ///
+ internal void Connect(Socket socket, int bufferSize = 1024)
+ {
+ if (_disposed != 0)
+ {
+ throw new ObjectDisposedException(nameof(NetClient));
+ }
+
+ if (_isConnected)
+ {
+ throw new InvalidOperationException("Already connected");
+ }
+
+ if (socket == null)
+ {
+ throw new ArgumentNullException(nameof(socket));
+ }
+
+ if (!socket.Connected)
+ {
+ throw new ArgumentException("Socket must be connected", nameof(socket));
+ }
+
+ try
+ {
+ socket.NoDelay = true;
+ InitializeClient(socket, bufferSize);
+ }
+ catch (Exception e)
+ {
+ // Clean up, but don't dispose the socket as we didn't create it.
+ _isConnected = false;
+ _bufferSize = 0;
+ _socket = null;
+
+ _receiveBuffer?.Dispose();
+ _receiveBuffer = null;
+
+ _receiveArg?.Dispose();
+ _receiveArg = null;
+
+ _sendArg?.Dispose();
+ _sendArg = null;
+
+ _outgoingChannel?.Writer.TryComplete();
+ _outgoingChannel = null;
+
+ SafeInvokeOnError(e);
+ throw;
+ }
+ }
+
+ ///
+ /// Stop the client with a specific reason
+ ///
+ /// Reason for closing the connection
+ /// Whether to include call stack information (expensive)
+ public void Stop(string reason = "Connection closed by client", bool includeCallStack = false)
+ {
+ string fullReason = reason;
+
+ // Only generate expensive stack trace when requested.
+ if (includeCallStack)
+ {
+ try
+ {
+ var stackTrace = new StackTrace(true);
+ var callStack = new List();
+ for (int i = 1; i < Math.Min(stackTrace.FrameCount, 10); i++) // Limit to 10 frames
+ {
+ var frame = stackTrace.GetFrame(i);
+ var method = frame?.GetMethod();
+ if (method != null)
+ {
+ var className = method.DeclaringType?.Name ?? "Unknown";
+ var methodName = method.Name;
+ callStack.Add($"{className}.{methodName}");
+ }
+ }
+
+ fullReason = $"{reason} (called from {string.Join(" -> ", callStack)})";
+ }
+ catch
+ {
+ // If stack trace fails, just use the original reason.
+ }
+ }
+
+ StopInternal(fullReason);
+ }
+
+ ///
+ /// Drains and cleans up the outgoing message channel.
+ ///
+ private void CleanupOutgoingChannel()
+ {
+ if (_outgoingChannel == null) return;
+ try
+ {
+ // This signals that no more items will be written to the channel.
+ _outgoingChannel.Writer.TryComplete();
+
+ // Drain any remaining messages in the channel.
+ while (_outgoingChannel.Reader.TryRead(out var outgoingMessage))
+ {
+ if (outgoingMessage.BufferWriter != null)
+ {
+ ReturnBufferToPool(outgoingMessage.BufferWriter);
+ }
+ }
+ }
+ catch (InvalidOperationException)
+ {
+ // Channel may have been completed and emptied by another thread.
+ }
+ catch (Exception e)
+ {
+ // Log other exceptions, as they might indicate a problem.
+ SafeInvokeOnError(e);
+ }
+ }
+
+ ///
+ /// Fast stop for high-frequency scenarios to avoid string allocations.
+ ///
+ /// Socket error code or exception type
+ /// Context where the error occurred
+ public void StopFast(int errorCode, string context)
+ {
+ var reason = $"{context}: {errorCode}";
+ StopInternal(reason);
+ }
+
+ ///
+ /// Internal stop implementation to avoid code duplication
+ ///
+ private void StopInternal(string fullReason)
+ {
+ if (Interlocked.CompareExchange(ref _stopping, 1, 0) == 1)
+ {
+ return;
+ }
+
+ try
+ {
+ if (!_isConnected)
+ {
+ CleanupOutgoingChannel();
+ return;
+ }
+
+ _isConnected = false;
+
+ try
+ {
+ _socket?.Shutdown(SocketShutdown.Both);
+ }
+ catch (Exception e)
+ {
+ SafeInvokeOnError(e);
+ }
+
+ _socket?.Close();
+ _socket?.Dispose();
+ _socket = null;
+
+ // Complete the channel writer before waiting for sends to prevent new messages.
+ _outgoingChannel?.Writer.TryComplete();
+
+ // Wait for pending sends to complete.
+ if (!SpinWait.SpinUntil(() => _sending == 0, TimeSpan.FromMilliseconds(100)))
+ {
+ // Force reset on timeout.
+ Interlocked.Exchange(ref _sending, 0);
+ }
+
+ // Clean up the current buffer writer.
+ var currentBufferWriter = Interlocked.Exchange(ref _currentBufferWriter, null);
+ if (currentBufferWriter != null)
+ {
+ ReturnBufferToPool(currentBufferWriter);
+ }
+
+ // Clean up remaining messages in channels.
+ CleanupOutgoingChannel();
+
+ _receiveArg?.Dispose();
+ _sendArg?.Dispose();
+ _receiveBuffer?.Dispose();
+
+ _receiveArg = null;
+ _sendArg = null;
+ _receiveBuffer = null;
+
+ _outgoingChannel = null;
+
+ _bufferSize = 0;
+
+ try
+ {
+ // Clear event handlers before invoking OnDisconnected to prevent memory leaks.
+ var onDisconnectedHandler = OnDisconnected;
+
+ OnConnected = null;
+ OnDisconnected = null;
+ OnDataReceived = null;
+ OnError = null;
+
+ onDisconnectedHandler?.Invoke(fullReason);
+ }
+ catch (Exception e)
+ {
+ SafeInvokeOnError(e);
+ }
+ }
+ finally
+ {
+ Interlocked.Exchange(ref _stopping, 0);
+ }
+ }
+
+ ///
+ /// Send data to the remote host via outgoing channel
+ ///
+ ///
+ /// Whether the data was queued successfully
+ public void Send(ReadOnlyMemory data)
+ {
+ if (Volatile.Read(ref _disposed) != 0 || !Volatile.Read(ref _isConnected) || Volatile.Read(ref _stopping) != 0)
+ {
+ return;
+ }
+
+ var bufferSize = _bufferSize;
+ if (bufferSize == 0)
+ {
+ return;
+ }
+
+ ArrayBufferWriter buffer1 = GetBufferFromPool();
+ ArrayBufferWriter buffer2 = null;
+
+ ResetBuffer(buffer1);
+
+ var span = buffer1.GetSpan(data.Length);
+ data.Span.CopyTo(span);
+ buffer1.Advance(data.Length);
+
+ try
+ {
+ if (_middlewares.Count > 0)
+ {
+ buffer2 = GetBufferFromPool();
+
+ ResetBuffer(buffer2);
+ var src = buffer1;
+ var dst = buffer2;
+
+ foreach (var middleware in _middlewares)
+ {
+ // Process using current src (input) -> dst (output).
+ middleware.ProcessSend(src.WrittenMemory, dst);
+
+ // The dst buffer is now the src for the next iteration.
+ (src, dst) = (dst, src);
+
+ // Clear the new dst buffer.
+ ResetBuffer(dst);
+ }
+
+ // `src` holds the final data, `dst` is temporary.
+ buffer1 = src;
+ ReturnBufferToPool(dst);
+ buffer2 = null; // Prevent double-return in `finally`.
+ }
+
+ data = buffer1.WrittenMemory;
+
+ if (data.Length > bufferSize)
+ {
+ SafeInvokeOnError(new ArgumentException(
+ $"Send data too large: {data.Length} bytes (max: {bufferSize})"));
+ return;
+ }
+
+ if (data.IsEmpty)
+ {
+ return;
+ }
+
+ try
+ {
+ var rawMessage = new RawMessage(buffer1, data.Length);
+
+ if (_outgoingChannel?.Writer.TryWrite(rawMessage) != true)
+ {
+ ReturnBufferToPool(buffer1);
+ Interlocked.Increment(ref _stats.OutgoingMessagesDropped);
+ return;
+ }
+
+ // Don't send if stopping.
+ if (Volatile.Read(ref _stopping) != 0)
+ {
+ return;
+ }
+
+ // Queue the message and trigger send.
+ Interlocked.Increment(ref _stats.MessagesSent);
+ Interlocked.Add(ref _stats.BytesSent, data.Length);
+
+ // Check for counter overflow.
+ if (Interlocked.Increment(ref _overflowCheckCounter) >= OverflowCheckFrequency)
+ {
+ Interlocked.Exchange(ref _overflowCheckCounter, 0);
+ _stats.ResetIfNearOverflow();
+ }
+
+ SendPending();
+ }
+ catch (Exception e)
+ {
+ // Return buffer on exception.
+ if (buffer1 != null)
+ {
+ ReturnBufferToPool(buffer1);
+ }
+ SafeInvokeOnError(e);
+ }
+ }
+ catch (Exception e)
+ {
+ SafeInvokeOnError(e);
+ }
+ finally
+ {
+ if (buffer2 != null) ReturnBufferToPool(buffer2);
+ }
+ }
+
+ ///
+ /// Send all pending data from the outgoing channel
+ ///
+ public void SendPending()
+ {
+ if (_disposed != 0 || !_isConnected || _stopping != 0)
+ {
+ return;
+ }
+
+ if (Interlocked.CompareExchange(ref _sending, 1, 0) == 1)
+ {
+ return;
+ }
+
+ TrySendNext();
+ }
+
+ ///
+ /// Try to send the next message from the outgoing channel
+ ///
+ private void TrySendNext()
+ {
+ if (_disposed != 0 || !_isConnected || _stopping != 0)
+ {
+ Interlocked.Exchange(ref _sending, 0);
+ return;
+ }
+
+ if (_outgoingChannel?.Reader.TryRead(out var rawMessage) != true)
+ {
+ Interlocked.Exchange(ref _sending, 0);
+ return;
+ }
+
+ SendInternal(rawMessage);
+ }
+
+ ///
+ /// Determines if a socket error indicates a normal connection closure rather than an error
+ ///
+ private static bool IsConnectionClosedError(SocketError error)
+ {
+ return error == SocketError.ConnectionAborted ||
+ error == SocketError.ConnectionReset ||
+ error == SocketError.Disconnecting ||
+ error == SocketError.Shutdown ||
+ error == SocketError.NotConnected ||
+ error == SocketError.TimedOut ||
+ error == SocketError.NetworkDown ||
+ error == SocketError.NetworkUnreachable ||
+ error == SocketError.HostDown ||
+ error == SocketError.HostUnreachable;
+ }
+
+ ///
+ /// Internal method to actually send preprocessed data over the socket
+ ///
+ private void SendInternal(RawMessage rawMessage)
+ {
+ if (_disposed != 0 || !_isConnected)
+ {
+ ReturnBufferToPool(rawMessage.BufferWriter);
+ Interlocked.Exchange(ref _sending, 0);
+ return;
+ }
+
+ var bufferSize = _bufferSize;
+ if (bufferSize == 0)
+ {
+ ReturnBufferToPool(rawMessage.BufferWriter);
+ Interlocked.Exchange(ref _sending, 0);
+ return;
+ }
+
+ try
+ {
+ var writtenMemory = rawMessage.BufferWriter.WrittenMemory.Slice(0, rawMessage.Length);
+
+ _sendArg.SetBuffer(MemoryMarshal.AsMemory(writtenMemory));
+
+ // Store buffer writer for cleanup after send.
+ var previousBufferWriter = Interlocked.Exchange(ref _currentBufferWriter, rawMessage.BufferWriter);
+ // Clean up previous writer to prevent leaks.
+ if (previousBufferWriter != null)
+ {
+ ReturnBufferToPool(previousBufferWriter);
+ }
+
+ if (!_socket.SendAsync(_sendArg))
+ {
+ HandleSendComplete(_sendArg);
+ }
+ }
+ catch (SocketException se)
+ {
+ ReturnBufferToPool(rawMessage.BufferWriter);
+
+ Interlocked.Exchange(ref _sending, 0);
+
+ // Don't report normal connection closure as an error.
+ if (!IsConnectionClosedError(se.SocketErrorCode))
+ {
+ SafeInvokeOnError(se);
+ }
+
+ StopFast((int)se.SocketErrorCode, "HandleReadWrite SocketException");
+ }
+ catch (Exception e)
+ {
+ ReturnBufferToPool(rawMessage.BufferWriter);
+
+ Interlocked.Exchange(ref _sending, 0);
+ SafeInvokeOnError(e);
+ // Stop with callstack for unexpected exceptions.
+ Stop("HandleSendComplete Exception", true);
+ }
+ }
+
+ private static void HandleReadWrite(object sender, SocketAsyncEventArgs args)
+ {
+ NetClient client = args.UserToken as NetClient;
+ try
+ {
+ if (client is not { IsConnected: true })
+ return;
+
+ switch (args.LastOperation)
+ {
+ case SocketAsyncOperation.Send:
+ client.HandleSendComplete(args);
+ break;
+ case SocketAsyncOperation.Receive:
+ Receive(args);
+ break;
+ default:
+ throw new InvalidOperationException($"Unknown operation: {args.LastOperation}");
+ }
+ }
+ catch (ObjectDisposedException)
+ {
+ // Ignore if socket is closed.
+ }
+ catch (SocketException se)
+ {
+ // Only invoke OnError if it's not a normal connection closure
+ if (!IsConnectionClosedError(se.SocketErrorCode))
+ {
+ client?.SafeInvokeOnError(se);
+ }
+
+ client?.StopFast((int)se.SocketErrorCode, "HandleReadWrite SocketException");
+ }
+ catch (Exception e)
+ {
+ client?.SafeInvokeOnError(e);
+ client?.Stop("HandleReadWrite Exception", true); // Include call stack for unexpected exceptions
+ }
+ }
+
+ private void HandleSendComplete(SocketAsyncEventArgs args)
+ {
+ // Get and clear the current buffer writer.
+ ArrayBufferWriter bufferWriterToReturn = Interlocked.Exchange(ref _currentBufferWriter, null);
+
+ try
+ {
+ args.SetBuffer(null, 0, 0);
+
+ if (args.SocketError != SocketError.Success)
+ {
+ Interlocked.Exchange(ref _sending, 0);
+
+ // Only invoke OnError if it's not a normal connection closure
+ if (!IsConnectionClosedError(args.SocketError))
+ {
+ SafeInvokeOnError(new SocketException((int)args.SocketError));
+ }
+
+ StopFast((int)args.SocketError, "HandleSendComplete SocketError");
+ return;
+ }
+
+ // Try to send the next message.
+ TrySendNext();
+ }
+ catch (Exception e)
+ {
+ Interlocked.Exchange(ref _sending, 0);
+ SafeInvokeOnError(e);
+ }
+ finally
+ {
+ // Ensure the buffer is always returned to the pool.
+ ReturnBufferToPool(bufferWriterToReturn);
+ }
+ }
+
+ private static void Receive(SocketAsyncEventArgs args)
+ {
+ NetClient client = (NetClient)args.UserToken!;
+
+ if (args is { BytesTransferred: > 0, SocketError: SocketError.Success })
+ {
+ try
+ {
+ if (client._receiveBuffer == null)
+ {
+ client.SafeInvokeOnError(CachedReceiveBufferNullException);
+ client.Stop("Receive buffer is null");
+ return;
+ }
+
+ client._receiveBuffer.AdvanceWrite(args.BytesTransferred);
+ client.ProcessReceivedData();
+ }
+ catch (Exception e)
+ {
+ client.SafeInvokeOnError(e);
+ }
+
+ if (!client._isConnected || client._socket == null || client._receiveBuffer == null)
+ {
+ return;
+ }
+
+ client.TryStartReceive(args);
+ }
+ else
+ {
+ if (client._isZeroByteReceive && args.SocketError == SocketError.Success)
+ {
+ client.TryStartReceive(args);
+ return;
+ }
+
+ if (args.SocketError != SocketError.Success)
+ {
+ client.StopFast((int)args.SocketError, "Socket error");
+ }
+ else if (args.BytesTransferred == 0)
+ {
+ // 0 bytes means remote graceful close.
+ var additionalInfo = "";
+ try
+ {
+ // Check socket state for more info.
+ if (client._socket != null)
+ {
+ var socketConnected = client._socket.Connected;
+ var socketAvailable = client._socket.Available;
+ additionalInfo = $" (Socket.Connected={socketConnected}, Available={socketAvailable})";
+
+ if (socketConnected && socketAvailable == 0)
+ {
+ additionalInfo += " - Appears to be graceful close";
+ }
+ else if (!socketConnected)
+ {
+ additionalInfo += " - Socket already marked as disconnected";
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ additionalInfo = $" (Socket check failed: {ex.Message})";
+ }
+
+ client.Stop($"Remote endpoint closed connection (0 bytes received){additionalInfo}");
+ }
+ else
+ {
+ client.Stop($"Unexpected disconnect (BytesTransferred: {args.BytesTransferred})");
+ }
+ }
+ }
+
+ ///
+ /// Check for complete messages in the receive buffer and directly invoke callbacks
+ ///
+ private void ProcessReceivedData()
+ {
+ if (_disposed != 0 || _receiveBuffer == null)
+ return;
+
+ if (_receiveBuffer.Length == 0)
+ {
+ return;
+ }
+
+ var bufferSize = _bufferSize;
+ if (bufferSize == 0)
+ {
+ return;
+ }
+
+ var data = _receiveBuffer.GetReadSegments();
+
+ byte[] temp = null;
+ ReadOnlyMemory src = data.First;
+
+ if (!data.Second.IsEmpty)
+ {
+ // Segmented data, use a temporary buffer.
+ var totalLength = data.Length;
+ temp = ArrayPool.Shared.Rent(totalLength);
+ Interlocked.Increment(ref _stats.TempBufferAllocations);
+ data.CopyTo(temp);
+ src = new ReadOnlyMemory(temp, 0, totalLength);
+ }
+
+ try
+ {
+ int totalConsumedFromBuffer = 0;
+
+ while (!src.IsEmpty)
+ {
+ ReadOnlyMemory receivedData = src;
+ int consumedFromOrigin = src.Length;
+
+ ArrayBufferWriter buffer1 = null;
+ if (_middlewares.Count > 0)
+ {
+ consumedFromOrigin = 0;
+
+ buffer1 = GetBufferFromPool();
+ var buffer2 = GetBufferFromPool();
+ ResetBuffer(buffer1);
+ ResetBuffer(buffer2);
+ var span = buffer1.GetSpan(src.Length);
+ src.Span.CopyTo(span);
+ buffer1.Advance(src.Length);
+
+ var middlewareSrc = buffer1;
+ var middlewareDst = buffer2;
+
+ // Process through middleware (reverse order to undo send transformations).
+ for (int i = _middlewares.Count - 1; i >= 0; i--)
+ {
+ try
+ {
+ var (halt, consumed) = _middlewares[i].ProcessReceive(middlewareSrc.WrittenMemory, middlewareDst);
+ // Accumulate consumption from middleware.
+ consumedFromOrigin += consumed;
+
+ if (halt)
+ {
+ // Halt processing and advance buffer.
+ totalConsumedFromBuffer += consumedFromOrigin;
+ _receiveBuffer.AdvanceRead(totalConsumedFromBuffer);
+ ReturnBufferToPool(buffer1);
+ ReturnBufferToPool(buffer2);
+ return;
+ }
+
+ // Swap buffers for next middleware.
+ (middlewareDst, middlewareSrc) = (middlewareSrc, middlewareDst);
+
+ // Clear the destination buffer for next use.
+ ResetBuffer(middlewareDst);
+ }
+ catch (Exception e)
+ {
+ SafeInvokeOnError(e);
+ // Halt and advance buffer on error.
+ totalConsumedFromBuffer += consumedFromOrigin;
+ _receiveBuffer.AdvanceRead(totalConsumedFromBuffer);
+ ReturnBufferToPool(buffer1);
+ ReturnBufferToPool(buffer2);
+ return;
+ }
+ }
+
+ // `middlewareSrc` has the final data.
+ receivedData = middlewareSrc.WrittenMemory;
+ buffer1 = middlewareSrc;
+ ReturnBufferToPool(middlewareDst);
+ }
+
+ // No more data, advance buffer and break.
+ if (receivedData.IsEmpty)
+ {
+ totalConsumedFromBuffer += consumedFromOrigin;
+ if (buffer1 != null)
+ {
+ ReturnBufferToPool(buffer1);
+ }
+ break;
+ }
+
+ // Invoke callback with processed data.
+ try
+ {
+ OnDataReceived?.Invoke(receivedData);
+ }
+ catch (Exception callbackEx)
+ {
+ // Log callback errors, but continue.
+ SafeInvokeOnError(callbackEx);
+ }
+ finally
+ {
+ if (buffer1 != null)
+ {
+ ReturnBufferToPool(buffer1);
+ }
+
+ // Track stats.
+ _localMessagesReceived++;
+ _localBytesReceived += consumedFromOrigin;
+
+ // Flush batched stats.
+ if (_localMessagesReceived >= DefaultConfig.BatchSize)
+ {
+ Interlocked.Add(ref _stats.MessagesReceived, _localMessagesReceived);
+ Interlocked.Add(ref _stats.BytesReceived, _localBytesReceived);
+ _localMessagesReceived = 0;
+ _localBytesReceived = 0;
+ }
+ }
+
+ totalConsumedFromBuffer += consumedFromOrigin;
+
+ if (consumedFromOrigin >= src.Length)
+ {
+ break;
+ }
+ src = src.Slice(consumedFromOrigin);
+
+ // Use SpinWait instead of Thread.Yield for better performance.
+ if (++_yieldCounter >= DefaultConfig.YieldThreshold)
+ {
+ _yieldCounter = 0;
+ Thread.Yield();
+ }
+
+ // Check for counter overflow.
+ if (Interlocked.Increment(ref _overflowCheckCounter) >= OverflowCheckFrequency)
+ {
+ Interlocked.Exchange(ref _overflowCheckCounter, 0);
+ _stats.ResetIfNearOverflow();
+ }
+ }
+
+ // Advance read position.
+ if (totalConsumedFromBuffer > 0)
+ {
+ _receiveBuffer.AdvanceRead(totalConsumedFromBuffer);
+ }
+ }
+ finally
+ {
+ // Return temp buffer to pool.
+ if (temp != null)
+ {
+ ArrayPool.Shared.Return(temp);
+ }
+
+ // Flush remaining batched stats.
+ if (_localMessagesReceived > 0)
+ {
+ Interlocked.Add(ref _stats.MessagesReceived, _localMessagesReceived);
+ Interlocked.Add(ref _stats.BytesReceived, _localBytesReceived);
+ _localMessagesReceived = 0;
+ _localBytesReceived = 0;
+ }
+ }
+ }
+
+ ///
+ /// Get detailed status information for debugging data loss issues
+ ///
+ public string GetDiagnosticInfo()
+ {
+ if (_disposed != 0)
+ return "NetClient disposed";
+
+ // Cache values for performance.
+ var stats = _stats;
+ var isConnected = IsConnected;
+ var hasPendingSends = HasPendingSends;
+ var bufferLength = _receiveBuffer?.Length ?? 0;
+ var bufferFreeSpace = _receiveBuffer?.FreeSpace ?? 0;
+ var bufferCapacity = _receiveBuffer?.Capacity ?? 0;
+ var isZeroByteReceive = _isZeroByteReceive;
+ var isSending = _sending != 0;
+
+ _diagnosticInfoBuilder.Clear();
+
+ _diagnosticInfoBuilder
+ .Append("NetClient ").Append(Id).AppendLine(" Diagnostics:")
+ .Append(" Connected: ").AppendLine(isConnected ? "True" : "False")
+ .Append(" Messages Received: ").AppendLine(stats.MessagesReceived.ToString())
+ .Append(" Outgoing Messages Dropped: ").Append(stats.OutgoingMessagesDropped)
+ .Append(" (Drop Rate: ").Append((stats.OutgoingDropRate * 100).ToString("F2")).AppendLine("%)")
+ .Append(" Messages Sent: ").AppendLine(stats.MessagesSent.ToString())
+ .Append(" Errors Skipped: ").AppendLine(stats.ErrorsSkipped.ToString())
+ .Append(" Temp Buffer Allocs: ").AppendLine(stats.TempBufferAllocations.ToString())
+ .Append(" Bytes Received: ").AppendLine(stats.BytesReceived.ToString())
+ .Append(" Bytes Sent: ").AppendLine(stats.BytesSent.ToString())
+ .Append(" Outgoing Channel Pending: ").AppendLine(hasPendingSends ? "Yes" : "No")
+ .Append(" Receive Buffer: ").Append(bufferLength).Append('/').Append(bufferCapacity)
+ .Append(" bytes (Free: ").Append(bufferFreeSpace).AppendLine(")")
+ .Append(" Zero-Byte Receive Mode: ").AppendLine(isZeroByteReceive ? "True" : "False")
+ .Append(" Sending: ").AppendLine(isSending ? "True" : "False");
+
+ return _diagnosticInfoBuilder.ToString();
+ }
+
+ ///
+ /// Dispose of resources
+ ///
+ public void Dispose()
+ {
+ // Ensure single-threaded disposal.
+ if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 1)
+ {
+ return;
+ }
+
+ Stop();
+
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Finalizer
+ ///
+ ~NetClient()
+ {
+ Dispose();
+ }
+ }
+}
diff --git a/Miku.Core/NetServer.cs b/Miku.Core/NetServer.cs
new file mode 100644
index 0000000..4ddfc52
--- /dev/null
+++ b/Miku.Core/NetServer.cs
@@ -0,0 +1,257 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+
+namespace Miku.Core
+{
+ ///
+ /// A server that listens for incoming connections from clients.
+ ///
+ public class NetServer : IDisposable
+ {
+ ///
+ /// Event that is raised when a new client connects to the server.
+ ///
+ public event Action OnClientConnected;
+
+ ///
+ /// Event that is raised when a client disconnects from the server.
+ ///
+ public event Action OnClientDisconnected;
+
+ ///
+ /// Event that is raised when a client sends data to the server.
+ ///
+ public event Action> OnClientDataReceived;
+
+ ///
+ /// Event that is raised when an error occurs.
+ ///
+ public event Action OnError;
+
+ ///
+ /// The size of the buffer used for sending and receiving data.
+ ///
+ public int BufferSize { get; set; } = 64 * 1024;
+
+ private Socket _listenSocket;
+ private SocketAsyncEventArgs _acceptEventArgs;
+ private readonly List _clients = new();
+ private readonly ReaderWriterLockSlim _clientsLock = new();
+ private volatile bool _isListening;
+ private int _disposed = 0;
+
+ ///
+ /// Whether the server is currently listening for connections
+ ///
+ public bool IsListening => _isListening && _disposed == 0;
+
+ ///
+ /// Get current client count in a thread-safe manner
+ ///
+ public int ClientCount
+ {
+ get
+ {
+ _clientsLock.EnterReadLock();
+ try
+ {
+ return _clients.Count;
+ }
+ finally
+ {
+ _clientsLock.ExitReadLock();
+ }
+ }
+ }
+
+ ///
+ /// Starts the server and begins listening for new connections.
+ ///
+ ///
+ ///
+ ///
+ public void Start(string ip, int port, int backLog = 1000)
+ {
+ if (_disposed != 0)
+ {
+ throw new ObjectDisposedException(nameof(NetServer));
+ }
+
+ if (_isListening)
+ {
+ throw new InvalidOperationException("Server is already listening");
+ }
+
+ if (string.IsNullOrWhiteSpace(ip))
+ {
+ throw new ArgumentException("IP address cannot be null or empty", nameof(ip));
+ }
+
+ if (port <= 0 || port > 65535)
+ {
+ throw new ArgumentException("Port must be between 1 and 65535", nameof(port));
+ }
+
+ try
+ {
+ _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
+ // Optimize server socket settings
+ _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
+ _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
+
+ _listenSocket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
+ _listenSocket.Listen(backLog);
+
+ // Set up the SocketAsyncEventArgs for accepting connections.
+ _acceptEventArgs = new SocketAsyncEventArgs();
+ _acceptEventArgs.Completed += ProcessAccept;
+
+ _isListening = true;
+
+ // Start the first accept operation.
+ StartAccept();
+ }
+ catch (Exception ex)
+ {
+ // Clean up on failure
+ _isListening = false;
+ _listenSocket?.Close();
+ _listenSocket?.Dispose();
+ _listenSocket = null;
+ _acceptEventArgs?.Dispose();
+ _acceptEventArgs = null;
+
+ OnError?.Invoke(ex);
+ throw;
+ }
+ }
+
+ ///
+ /// Stops the server from listening for new connections.
+ ///
+ public void Stop()
+ {
+ if (!_isListening) return;
+
+ _isListening = false;
+
+ try
+ {
+ _listenSocket?.Close();
+ }
+ catch (Exception ex)
+ {
+ OnError?.Invoke(ex);
+ }
+ finally
+ {
+ _listenSocket?.Dispose();
+ _listenSocket = null;
+ }
+
+ _clientsLock.EnterWriteLock();
+ try
+ {
+ // Stop all clients, make a copy of the list to avoid modifying it while iterating.
+ foreach (var client in _clients.ToArray())
+ {
+ try
+ {
+ client.Stop("Server shutting down");
+ }
+ catch (Exception ex)
+ {
+ OnError?.Invoke(ex);
+ }
+ }
+
+ _clients.Clear();
+ }
+ finally
+ {
+ _clientsLock.ExitWriteLock();
+ }
+
+ _acceptEventArgs?.Dispose();
+ _acceptEventArgs = null;
+ }
+
+ private void StartAccept()
+ {
+ if (!_isListening) return;
+
+ _acceptEventArgs.AcceptSocket = null;
+
+ if (!_listenSocket.AcceptAsync(_acceptEventArgs))
+ {
+ ProcessAccept(null, _acceptEventArgs);
+ }
+ }
+
+ private void ProcessAccept(object sender, SocketAsyncEventArgs e)
+ {
+ if (e.SocketError == SocketError.Success)
+ {
+ // Retrieve the accepted socket.
+ Socket acceptedSocket = e.AcceptSocket;
+
+ // Create a new NetClient using the accepted socket.
+#pragma warning disable IDISP001
+ NetClient client = new NetClient();
+#pragma warning restore IDISP001
+
+ _clientsLock.EnterWriteLock();
+ try
+ {
+ _clients.Add(client);
+ }
+ finally
+ {
+ _clientsLock.ExitWriteLock();
+ }
+
+ client.OnConnected += () => OnClientConnected?.Invoke(client);
+ client.OnDisconnected += reason =>
+ {
+ OnClientDisconnected?.Invoke(client, reason);
+ _clientsLock.EnterWriteLock();
+ try
+ {
+ _clients.Remove(client);
+ }
+ finally
+ {
+ _clientsLock.ExitWriteLock();
+ }
+ };
+ client.OnDataReceived += data => OnClientDataReceived?.Invoke(client, data);
+ client.OnError += OnError;
+ client.Connect(acceptedSocket, BufferSize);
+ }
+ // If the accept operation was canceled, then the server is stopped.
+ else if (e.SocketError != SocketError.Interrupted && e.SocketError != SocketError.OperationAborted)
+ {
+ OnError?.Invoke(new SocketException((int)e.SocketError));
+ }
+
+ // Continue accepting the next connection only if still listening
+ if (_isListening && _listenSocket != null)
+ {
+ StartAccept();
+ }
+ }
+
+ public void Dispose()
+ {
+ if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
+ {
+ Stop();
+ _clientsLock?.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/README.md b/README.md
index b28a82a..63244b6 100644
--- a/README.md
+++ b/README.md
@@ -109,6 +109,36 @@ await ftpServer.StopAsync();
## Configuration
+### Passive Data Ports
+
+Every PASV command binds one listener from the configured range, and holds that port until the
+transfer ends, the client disconnects, or the idle timeout expires:
+
+```csharp
+var serverOptions = Options.Create(new FtpServerConfigurationOptions
+{
+ PasvMinPort = 50000,
+ PasvMaxPort = 50100,
+ PasvIdleTimeout = TimeSpan.FromMinutes(2)
+});
+```
+
+Size the range for the peak number of *concurrent* transfers, with headroom for ports still in
+`TIME_WAIT` after a download. Ports are handed out round-robin, so a port that was just released is
+the last one retried.
+
+`PasvIdleTimeout` bounds how long a passive listener waits for the client to dial in. Clients that
+issue PASV and then never connect — aborted transfers, dropped networks — are the usual cause of a
+drained range; the timeout reclaims their ports. It is disarmed the moment the data connection is
+accepted, so it never cuts a slow transfer short. Set it to `Timeout.InfiniteTimeSpan` to wait
+forever.
+
+Setting `PasvMinPort` and `PasvMaxPort` to `0` disables the range entirely and lets the operating
+system assign an ephemeral port per data connection, which is only appropriate when no firewall or
+NAT rule constrains the passive ports. When a configured range runs dry the server falls back to an
+ephemeral port and logs a warning — that port will usually be blocked by a firewall rule scoped to
+the range, so the warning is worth alerting on.
+
### Logging
The library uses `Microsoft.Extensions.Logging`. When using DI, it will automatically use the configured logging providers (e.g., Serilog, Console, Debug).