Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion FmiSrl.FtpServer.Server/Abstractions/FtpCommandContext.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using FmiSrl.FtpServer.Server.Infrastructure;
using Microsoft.Extensions.Logging;

namespace FmiSrl.FtpServer.Server.Abstractions;
Expand All @@ -13,6 +14,12 @@ namespace FmiSrl.FtpServer.Server.Abstractions;
/// <param name="Configuration">The server configuration options.</param>
/// <param name="Logger">The logger to use for recording command execution details.</param>
/// <param name="EventHandlers">The collection of registered FTP server event handlers.</param>
/// <param name="PassivePorts">
/// The server-wide <see cref="PassivePortPool"/> that PASV leases data ports from, or <c>null</c>
/// to let the command build a throwaway pool from <paramref name="Configuration"/>. Supplying the
/// shared pool is what stops two concurrent sessions from being handed the same port; the
/// <c>null</c> fallback exists only for contexts constructed by hand outside a running server.
/// </param>
public record FtpCommandContext(
IFtpSession Session,
string Verb,
Expand All @@ -21,7 +28,8 @@ public record FtpCommandContext(
IAuthenticationProvider Authenticator,
FtpServerConfigurationOptions Configuration,
ILogger Logger,
IEnumerable<IFtpServerEventHandler>? EventHandlers = null
IEnumerable<IFtpServerEventHandler>? EventHandlers = null,
PassivePortPool? PassivePorts = null
)
{
/// <summary>
Expand Down
80 changes: 67 additions & 13 deletions FmiSrl.FtpServer.Server/Commands/PasvCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -25,33 +26,86 @@ 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
);
/// <remarks>
/// 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.
/// </remarks>
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<PassiveDataConnection?> 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);

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}).");
}

Expand Down
7 changes: 5 additions & 2 deletions FmiSrl.FtpServer.Server/FmiSrl.FtpServer.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@
<Authors>FMI S.r.l.</Authors>
<Copyright>Copyright 2026 FMI S.r.l.</Copyright>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.6" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.6" />
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.6" />
<PackageReference Include="Miku" Version="2.0.0"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Miku.Core\Miku.Core.csproj" />
</ItemGroup>

</Project>
9 changes: 8 additions & 1 deletion FmiSrl.FtpServer.Server/FtpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ public class FtpServer(
private readonly FtpCommandHandler _commandHandler = new(middlewares);
private readonly ConcurrentDictionary<int, IFtpSession> _sessions = new();

/// <remarks>
/// 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.
/// </remarks>
private readonly PassivePortPool _passivePorts = new(configurationOptions.Value, logger);

private NetServer? _netServer;

private void RegisterCommands()
Expand Down Expand Up @@ -189,7 +195,8 @@ private async Task ExecuteCommandAsync(NetClient client, FtpSession session, str
_authenticationProvider,
_configurationOptions,
_logger,
_eventHandlers);
_eventHandlers,
_passivePorts);

await _commandHandler.HandleCommandAsync(context);

Expand Down
32 changes: 28 additions & 4 deletions FmiSrl.FtpServer.Server/FtpServerConfigurationOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,41 @@ public class FtpServerConfigurationOptions
/// <summary>
/// Gets or sets the minimum port number in the range for passive data connections.
/// </summary>
/// <value>The minimum passive port as an <see cref="int"/>. Defaults to 50000.</value>
[Range(1, 65535)]
/// <value>
/// The minimum passive port as an <see cref="int"/>. 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.
/// </value>
/// <remarks>
/// Size the range for the peak number of concurrent transfers, with headroom: each finished
/// download keeps its port in <c>TIME_WAIT</c> for a while afterwards. The server logs a
/// warning and falls back to an ephemeral port whenever the range runs dry.
/// </remarks>
[Range(0, 65535)]
public int PasvMinPort { get; set; } = 50000;

/// <summary>
/// Gets or sets the maximum port number in the range for passive data connections.
/// </summary>
/// <value>The maximum passive port as an <see cref="int"/>. Defaults to 50100.</value>
[Range(1, 65535)]
/// <value>The maximum passive port as an <see cref="int"/>. Defaults to 50100. Must not be lower than <see cref="PasvMinPort"/>.</value>
[Range(0, 65535)]
public int PasvMaxPort { get; set; } = 50100;

/// <summary>
/// Gets or sets how long a passive listener waits for the client's data connection before the
/// port is reclaimed.
/// </summary>
/// <value>
/// The wait as a <see cref="TimeSpan"/>. Defaults to two minutes. Set it to
/// <see cref="Timeout.InfiniteTimeSpan"/> to wait indefinitely, which risks draining the
/// passive range whenever clients issue PASV and then abandon the transfer.
/// </value>
/// <remarks>
/// 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.
/// </remarks>
public TimeSpan PasvIdleTimeout { get; set; } = TimeSpan.FromMinutes(2);

/// <summary>
/// Gets or sets the name of the FTP server presented in the welcome message.
/// </summary>
Expand Down
Loading
Loading