Skip to content

Commit efb24a9

Browse files
committed
Connection logger is deprecated
Errors are closing the connection gracefully.
1 parent f7d3ac6 commit efb24a9

18 files changed

Lines changed: 199 additions & 57 deletions

samples/TestFtpServer/ServiceCollectionExtensions.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ public static IServiceCollection AddFtpServices(
199199
TlsEnableServerCommandHandler.EnableTlsAsync(
200200
e.Connection,
201201
authTlsOptions.Value.ServerCertificate,
202+
serviceProvider.GetService<ILogger<TlsEnableServerCommandHandler>>(),
202203
CancellationToken.None).Wait();
203204
};
204205
}

src/FubarDev.FtpServer.Abstractions/Commands/DefaultFtpCommandDispatcher.cs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ public class DefaultFtpCommandDispatcher : IFtpCommandDispatcher
3333
[NotNull]
3434
private readonly IFtpCommandActivator _commandActivator;
3535

36+
[CanBeNull]
37+
private readonly ILogger<DefaultFtpCommandDispatcher> _logger;
38+
3639
[NotNull]
3740
private readonly FtpCommandExecutionDelegate _executionDelegate;
3841

@@ -43,15 +46,18 @@ public class DefaultFtpCommandDispatcher : IFtpCommandDispatcher
4346
/// <param name="loginStateMachine">The login state machine.</param>
4447
/// <param name="commandActivator">The command activator.</param>
4548
/// <param name="middlewareObjects">The list of middleware objects.</param>
49+
/// <param name="logger">The logger.</param>
4650
public DefaultFtpCommandDispatcher(
4751
[NotNull] IFtpConnection connection,
4852
[NotNull] IFtpLoginStateMachine loginStateMachine,
4953
[NotNull] IFtpCommandActivator commandActivator,
50-
[NotNull, ItemNotNull] IEnumerable<IFtpCommandMiddleware> middlewareObjects)
54+
[NotNull, ItemNotNull] IEnumerable<IFtpCommandMiddleware> middlewareObjects,
55+
[CanBeNull] ILogger<DefaultFtpCommandDispatcher> logger = null)
5156
{
5257
_connection = connection;
5358
_loginStateMachine = loginStateMachine;
5459
_commandActivator = commandActivator;
60+
_logger = logger;
5561
var nextStep = new FtpCommandExecutionDelegate(ExecuteCommandAsync);
5662
foreach (var middleware in middlewareObjects.Reverse())
5763
{
@@ -62,9 +68,6 @@ public DefaultFtpCommandDispatcher(
6268
_executionDelegate = nextStep;
6369
}
6470

65-
[CanBeNull]
66-
private ILogger Log => _connection.Log;
67-
6871
/// <inheritdoc />
6972
public async Task DispatchAsync(FtpContext context, CancellationToken cancellationToken)
7073
{
@@ -184,7 +187,7 @@ private async Task ExecuteCommandAsync(
184187
response = new FtpResponse(
185188
425,
186189
validationException.Message);
187-
Log?.LogWarning(validationException.Message);
190+
_logger?.LogWarning(validationException.Message);
188191
break;
189192

190193
case OperationCanceledException _:
@@ -195,21 +198,21 @@ private async Task ExecuteCommandAsync(
195198
case FileSystemException fse:
196199
{
197200
var message = fse.Message != null ? $"{fse.FtpErrorName}: {fse.Message}" : fse.FtpErrorName;
198-
Log?.LogInformation($"Rejected command ({command}) with error {fse.FtpErrorCode} {message}");
201+
_logger?.LogInformation($"Rejected command ({command}) with error {fse.FtpErrorCode} {message}");
199202
response = new FtpResponse(fse.FtpErrorCode, message);
200203
break;
201204
}
202205

203206
case NotSupportedException nse:
204207
{
205208
var message = nse.Message ?? T("Command {0} not supported", command);
206-
Log?.LogInformation(message);
209+
_logger?.LogInformation(message);
207210
response = new FtpResponse(502, message);
208211
break;
209212
}
210213

211214
default:
212-
Log?.LogError(0, ex, "Failed to process message ({0})", command);
215+
_logger?.LogError(0, ex, "Failed to process message ({0})", command);
213216
response = new FtpResponse(501, T("Syntax error in parameters or arguments."));
214217
break;
215218
}
@@ -224,7 +227,7 @@ await SendResponseAsync(response, context.Connection.CancellationToken)
224227
}
225228
catch (Exception ex) when (ex.Is<OperationCanceledException>())
226229
{
227-
Log?.LogWarning("Sending the response cancelled: {response}", response);
230+
_logger?.LogWarning("Sending the response cancelled: {response}", response);
228231
}
229232
}
230233
}

src/FubarDev.FtpServer.Abstractions/ConnectionExtensions.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,15 @@ public static class ConnectionExtensions
2424
/// </summary>
2525
/// <param name="connection">The connection to get the response socket from.</param>
2626
/// <param name="asyncSendAction">The action to perform with a working response socket.</param>
27+
/// <param name="logger">The logger.</param>
2728
/// <param name="cancellationToken">The cancellation token.</param>
2829
/// <returns>The task with the FTP response.</returns>
2930
[NotNull]
3031
[ItemNotNull]
3132
public static async Task<IFtpResponse> SendDataAsync(
3233
[NotNull] this IFtpConnection connection,
3334
[NotNull] Func<IFtpDataConnection, CancellationToken, Task<IFtpResponse>> asyncSendAction,
35+
[CanBeNull] ILogger logger,
3436
CancellationToken cancellationToken)
3537
{
3638
IFtpDataConnection dataConnection;
@@ -41,7 +43,7 @@ public static async Task<IFtpResponse> SendDataAsync(
4143
}
4244
catch (Exception ex)
4345
{
44-
connection.Log?.LogWarning(0, ex, "Could not open data connection: {error}", ex.Message);
46+
logger?.LogWarning(0, ex, "Could not open data connection: {error}", ex.Message);
4547
var localizationFeature = connection.Features.Get<ILocalizationFeature>();
4648
return new FtpResponse(425, localizationFeature.Catalog.GetString("Could not open data connection"));
4749
}

src/FubarDev.FtpServer.Abstractions/DataConnection/PassiveDataConnectionFeatureFactory.cs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ public class PassiveDataConnectionFeatureFactory
3131
[NotNull]
3232
private readonly IFtpConnectionAccessor _connectionAccessor;
3333

34+
[CanBeNull]
35+
private readonly ILogger<PassiveDataConnectionFeatureFactory> _logger;
36+
3437
[NotNull]
3538
[ItemNotNull]
3639
private readonly List<IFtpDataConnectionValidator> _validators;
@@ -41,13 +44,16 @@ public class PassiveDataConnectionFeatureFactory
4144
/// <param name="pasvListenerFactory">The PASV listener factory.</param>
4245
/// <param name="connectionAccessor">The FTP connection accessor.</param>
4346
/// <param name="validators">An enumeration of FTP connection validators.</param>
47+
/// <param name="logger">The logger.</param>
4448
public PassiveDataConnectionFeatureFactory(
4549
[NotNull] IPasvListenerFactory pasvListenerFactory,
4650
[NotNull] IFtpConnectionAccessor connectionAccessor,
47-
[NotNull] [ItemNotNull] IEnumerable<IFtpDataConnectionValidator> validators)
51+
[NotNull] [ItemNotNull] IEnumerable<IFtpDataConnectionValidator> validators,
52+
[CanBeNull] ILogger<PassiveDataConnectionFeatureFactory> logger = null)
4853
{
4954
_pasvListenerFactory = pasvListenerFactory;
5055
_connectionAccessor = connectionAccessor;
56+
_logger = logger;
5157
_validators = validators.ToList();
5258
}
5359

@@ -71,7 +77,13 @@ public async Task<IFtpDataConnectionFeature> CreateFeatureAsync(
7177
addressFamily,
7278
0,
7379
cancellationToken).ConfigureAwait(false);
74-
return new PassiveDataConnectionFeature(listener, _validators, ftpCommand, connection, listener.PasvEndPoint);
80+
return new PassiveDataConnectionFeature(
81+
listener,
82+
_validators,
83+
ftpCommand,
84+
connection,
85+
listener.PasvEndPoint,
86+
_logger);
7587
}
7688

7789
private class PassiveDataConnectionFeature : IFtpDataConnectionFeature
@@ -86,16 +98,21 @@ private class PassiveDataConnectionFeature : IFtpDataConnectionFeature
8698
[NotNull]
8799
private readonly IFtpConnection _ftpConnection;
88100

101+
[CanBeNull]
102+
private readonly ILogger _logger;
103+
89104
public PassiveDataConnectionFeature(
90105
[NotNull] IPasvListener listener,
91106
[NotNull] [ItemNotNull] List<IFtpDataConnectionValidator> validators,
92107
[NotNull] FtpCommand command,
93108
[NotNull] IFtpConnection ftpConnection,
94-
[NotNull] IPEndPoint localEndPoint)
109+
[NotNull] IPEndPoint localEndPoint,
110+
[CanBeNull] ILogger logger)
95111
{
96112
_listener = listener;
97113
_validators = validators;
98114
_ftpConnection = ftpConnection;
115+
_logger = logger;
99116
LocalEndPoint = localEndPoint;
100117
Command = command;
101118
}
@@ -140,7 +157,7 @@ public async Task<IFtpDataConnection> GetDataConnectionAsync(TimeSpan timeout, C
140157
}
141158
}
142159

143-
_ftpConnection.Log?.LogDebug($"Data connection accepted from {dataConnection.RemoteAddress}");
160+
_logger?.LogDebug($"Data connection accepted from {dataConnection.RemoteAddress}");
144161

145162
return dataConnection;
146163
}

src/FubarDev.FtpServer.Abstractions/IFtpConnection.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ public interface IFtpConnection : IConnectionFeature, IDisposable
6161
/// Gets the FTP connection logger.
6262
/// </summary>
6363
[CanBeNull]
64+
[Obsolete("Use your own logger instead of the one from the connection.")]
6465
ILogger Log { get; }
6566

6667
/// <summary>

src/FubarDev.FtpServer.Commands/CommandExtensions/SiteBlstCommandExtension.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,20 @@ public class SiteBlstCommandExtension : FtpCommandHandlerExtension
2929
[NotNull]
3030
private readonly IBackgroundTransferWorker _backgroundTransferWorker;
3131

32+
[CanBeNull]
33+
private readonly ILogger<SiteBlstCommandExtension> _logger;
34+
3235
/// <summary>
3336
/// Initializes a new instance of the <see cref="SiteBlstCommandExtension"/> class.
3437
/// </summary>
3538
/// <param name="backgroundTransferWorker">The background transfer worker service.</param>
39+
/// <param name="logger">The logger.</param>
3640
public SiteBlstCommandExtension(
37-
[NotNull] IBackgroundTransferWorker backgroundTransferWorker)
41+
[NotNull] IBackgroundTransferWorker backgroundTransferWorker,
42+
[CanBeNull] ILogger<SiteBlstCommandExtension> logger = null)
3843
{
3944
_backgroundTransferWorker = backgroundTransferWorker;
45+
_logger = logger;
4046
}
4147

4248
/// <inheritdoc/>
@@ -90,6 +96,7 @@ await FtpContext.ServerCommandWriter.WriteAsync(
9096

9197
return await Connection.SendDataAsync(
9298
ExecuteSend,
99+
_logger,
93100
cancellationToken)
94101
.ConfigureAwait(false);
95102
}
@@ -105,7 +112,7 @@ private async Task<IFtpResponse> ExecuteSend(IFtpDataConnection dataConnection,
105112
{
106113
foreach (var line in GetLines(_backgroundTransferWorker.GetStates()))
107114
{
108-
Connection.Log?.LogDebug(line);
115+
_logger?.LogDebug(line);
109116
await writer.WriteLineAsync(line).ConfigureAwait(false);
110117
}
111118
}

src/FubarDev.FtpServer.Commands/CommandHandlers/AppeCommandHandler.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
using JetBrains.Annotations;
1919

20+
using Microsoft.Extensions.Logging;
21+
2022
namespace FubarDev.FtpServer.CommandHandlers
2123
{
2224
/// <summary>
@@ -28,14 +30,20 @@ public class AppeCommandHandler : FtpCommandHandler
2830
[NotNull]
2931
private readonly IBackgroundTransferWorker _backgroundTransferWorker;
3032

33+
[CanBeNull]
34+
private readonly ILogger<AppeCommandHandler> _logger;
35+
3136
/// <summary>
3237
/// Initializes a new instance of the <see cref="AppeCommandHandler"/> class.
3338
/// </summary>
3439
/// <param name="backgroundTransferWorker">The background transfer worker service.</param>
40+
/// <param name="logger">The logger.</param>
3541
public AppeCommandHandler(
36-
[NotNull] IBackgroundTransferWorker backgroundTransferWorker)
42+
[NotNull] IBackgroundTransferWorker backgroundTransferWorker,
43+
[CanBeNull] ILogger<AppeCommandHandler> logger = null)
3744
{
3845
_backgroundTransferWorker = backgroundTransferWorker;
46+
_logger = logger;
3947
}
4048

4149
/// <inheritdoc/>
@@ -78,6 +86,7 @@ await FtpContext.ServerCommandWriter
7886
return await Connection
7987
.SendDataAsync(
8088
(dataConnection, ct) => ExecuteSend(dataConnection, fileInfo, restartPosition, ct),
89+
_logger,
8190
cancellationToken)
8291
.ConfigureAwait(false);
8392
}

src/FubarDev.FtpServer.Commands/CommandHandlers/ListCommandHandler.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
using FubarDev.FtpServer.ServerCommands;
2323
using FubarDev.FtpServer.Utilities;
2424

25+
using JetBrains.Annotations;
26+
2527
using Microsoft.Extensions.Logging;
2628

2729
namespace FubarDev.FtpServer.CommandHandlers
@@ -34,6 +36,19 @@ namespace FubarDev.FtpServer.CommandHandlers
3436
[FtpCommandHandler("LS")]
3537
public class ListCommandHandler : FtpCommandHandler
3638
{
39+
[CanBeNull]
40+
private readonly ILogger<ListCommandHandler> _logger;
41+
42+
/// <summary>
43+
/// Initializes a new instance of the <see cref="ListCommandHandler"/> class.
44+
/// </summary>
45+
/// <param name="logger">The logger.</param>
46+
public ListCommandHandler(
47+
[CanBeNull] ILogger<ListCommandHandler> logger = null)
48+
{
49+
_logger = logger;
50+
}
51+
3752
/// <inheritdoc/>
3853
public override async Task<IFtpResponse> Process(FtpCommand command, CancellationToken cancellationToken)
3954
{
@@ -45,6 +60,7 @@ await FtpContext.ServerCommandWriter
4560

4661
return await Connection.SendDataAsync(
4762
(dataConnection, ct) => ExecuteSend(dataConnection, command, ct),
63+
_logger,
4864
cancellationToken)
4965
.ConfigureAwait(false);
5066
}
@@ -141,7 +157,7 @@ private async Task<IFtpResponse> ExecuteSend(IFtpDataConnection dataConnection,
141157
if (argument.Recursive)
142158
{
143159
var line = currentPath.ToDisplayString() + ":";
144-
Connection.Log?.LogTrace(line);
160+
_logger?.LogTrace(line);
145161
await writer.WriteLineAsync(line).ConfigureAwait(false);
146162
}
147163

@@ -191,7 +207,7 @@ private async Task<IFtpResponse> ExecuteSend(IFtpDataConnection dataConnection,
191207
}
192208

193209
var line = formatter.Format(entry, name);
194-
Connection.Log?.LogTrace(line);
210+
_logger?.LogTrace(line);
195211
await writer.WriteLineAsync(line).ConfigureAwait(false);
196212
}
197213
}

src/FubarDev.FtpServer.Commands/CommandHandlers/MlstCommandHandler.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,19 @@ public class MlstCommandHandler : FtpCommandHandler
3737
/// </summary>
3838
internal static readonly ISet<string> KnownFacts = new HashSet<string> { "type", "size", "perm", "modify", "create" };
3939

40+
[CanBeNull]
41+
private readonly ILogger<MlstCommandHandler> _logger;
42+
43+
/// <summary>
44+
/// Initializes a new instance of the <see cref="MlstCommandHandler"/> class.
45+
/// </summary>
46+
/// <param name="logger">The logger.</param>
47+
public MlstCommandHandler(
48+
[CanBeNull] ILogger<MlstCommandHandler> logger = null)
49+
{
50+
_logger = logger;
51+
}
52+
4053
/// <summary>
4154
/// Gets the feature string for the <c>MFF</c> command.
4255
/// </summary>
@@ -147,6 +160,7 @@ await FtpContext.ServerCommandWriter
147160
var factsFeature = Connection.Features.Get<IMlstFactsFeature>() ?? CreateMlstFactsFeature();
148161
return await Connection.SendDataAsync(
149162
(dataConnection, ct) => ExecuteSendAsync(dataConnection, authInfoFeature.User, fsFeature.FileSystem, path, dirEntry, factsFeature, ct),
163+
_logger,
150164
cancellationToken)
151165
.ConfigureAwait(false);
152166
}
@@ -175,7 +189,7 @@ private async Task<IFtpResponse> ExecuteSendAsync(
175189
var name = enumerator.Name;
176190
var entry = enumerator.Entry;
177191
var line = formatter.Format(entry, name);
178-
Connection.Log?.LogTrace(line);
192+
_logger?.LogTrace(line);
179193
await writer.WriteLineAsync(line).ConfigureAwait(false);
180194
}
181195

0 commit comments

Comments
 (0)