Skip to content

Commit

Permalink
new FtpConfig system
Browse files Browse the repository at this point in the history
  • Loading branch information
robinrodricks committed Aug 27, 2022
1 parent 32c62a9 commit bc0cc4c
Show file tree
Hide file tree
Showing 90 changed files with 1,276 additions and 1,293 deletions.
8 changes: 4 additions & 4 deletions FluentFTP.CSharpExamples/ConnectFTPS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ internal static class ConnectFTPSExample {

public static void ConnectFTPS() {
using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
conn.EncryptionMode = FtpEncryptionMode.Explicit;
conn.ValidateAnyCertificate = true;
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit;
conn.Config.ValidateAnyCertificate = true;
conn.Connect();
}
}
Expand All @@ -19,8 +19,8 @@ public static async Task ConnectFTPSAsync() {
var token = new CancellationToken();
using (var conn = new AsyncFtpClient("127.0.0.1", "ftptest", "ftptest")) {

conn.EncryptionMode = FtpEncryptionMode.Explicit;
conn.ValidateAnyCertificate = true;
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit;
conn.Config.ValidateAnyCertificate = true;
await conn.Connect(token);
}
}
Expand Down
4 changes: 2 additions & 2 deletions FluentFTP.CSharpExamples/ConnectFTPSCertificate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ internal static class ConnectFTPSCertificateExample {

public static void ConnectFTPSCertificate() {
using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
conn.EncryptionMode = FtpEncryptionMode.Explicit;
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit;
conn.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
conn.Connect();
}
Expand All @@ -20,7 +20,7 @@ public static async Task ConnectFTPSCertificateAsync() {
var token = new CancellationToken();
using (var conn = new AsyncFtpClient("127.0.0.1", "ftptest", "ftptest")) {

conn.EncryptionMode = FtpEncryptionMode.Explicit;
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit;
conn.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
await conn.Connect(token);
}
Expand Down
2 changes: 1 addition & 1 deletion FluentFTP.CSharpExamples/CustomParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ internal static class CustomParser {
/// Adds a custom file listing parser
/// </summary>
public static void AddCustomParser(FtpClient client) {
client.ListingCustomParser = ParseUnixList;
client.Config.ListingCustomParser = ParseUnixList;
}

/// <summary>
Expand Down
39 changes: 18 additions & 21 deletions FluentFTP.CSharpExamples/LocalIpAddress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,43 @@
using System.Text;
using System.Threading.Tasks;

namespace CSharpExamples
{
namespace CSharpExamples {
using System.Net;
using System.Net.Sockets;

using FluentFTP;

public static class LocalIpAddress
{
public static void LocaIpAddressExample()
{
public static class LocalIpAddress {
public static void LocaIpAddressExample() {

// IP addresses for current host inside myprivatedomain
var localIpAddresses = new[]
{
IPAddress.Parse("10.244.191.143"),
IPAddress.Parse("fcec:177:cfbd:6555:8f8c::1")
};
{
IPAddress.Parse("10.244.191.143"),
IPAddress.Parse("fcec:177:cfbd:6555:8f8c::1")
};

foreach (var localIpAddress in localIpAddresses) {

foreach (var localIpAddress in localIpAddresses)
{
// let's say that ftp.myprivatedomain has ipv4 and ipv5 addresses
using (var f = new FtpClient("ftp.myprivatedomain", "test", "test")
{
InternetProtocolVersions = localIpAddress.AddressFamily == AddressFamily.InterNetworkV6 ? FtpIpVersion.IPv6 : FtpIpVersion.IPv4,
using var f = new FtpClient("ftp.myprivatedomain", "test", "test");

// Equivalent to lftp's ftp:port-ipv[4|6] and net:socket-bind-ipv[4|6] (see http://manpages.org/lftp)
SocketLocalIp = localIpAddress
})
f.Config.InternetProtocolVersions = localIpAddress.AddressFamily == AddressFamily.InterNetworkV6 ? FtpIpVersion.IPv6 : FtpIpVersion.IPv4;

// Equivalent to lftp's ftp:port-ipv[4|6] and net:socket-bind-ipv[4|6] (see http://manpages.org/lftp)
f.Config.SocketLocalIp = localIpAddress;
{
f.Connect();

Console.WriteLine($"Connected to {f.SocketRemoteEndPoint} from {f.SocketLocalEndPoint}");
foreach (var file in f.GetListing())
{
foreach (var file in f.GetListing()) {
Console.Out.WriteLine(file);
}

f.Disconnect();
}
}
}

}
}
}
8 changes: 4 additions & 4 deletions FluentFTP.Tests/Unit/TimeoutTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ private void ValidateTime(DateTime callStart, string methodName) {
public void ConnectTimeout() {

var client = new FtpClient("test.github.com", 21, "wrong", "password");
client.DataConnectionType = FtpDataConnectionType.PASVEX;
client.ConnectTimeout = timeoutMillis;
client.Config.DataConnectionType = FtpDataConnectionType.PASVEX;
client.Config.ConnectTimeout = timeoutMillis;
var start = DateTime.Now;
try {
client.Connect();
Expand All @@ -43,8 +43,8 @@ public void ConnectTimeout() {
public async Task ConnectTimeoutAsync() {

var client = new AsyncFtpClient("test.github.com", 21, "wrong", "password");
client.DataConnectionType = FtpDataConnectionType.PASVEX;
client.ConnectTimeout = timeoutMillis;
client.Config.DataConnectionType = FtpDataConnectionType.PASVEX;
client.Config.ConnectTimeout = timeoutMillis;
var start = DateTime.Now;
try {
await client.Connect();
Expand Down
6 changes: 3 additions & 3 deletions FluentFTP.Tests/Unit/TimezoneTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ public void TokyoToLocal() {
}

private static void AssertConvertedDateTime(FtpClient client, FtpDate conversion, double tz, string input, string expected) {
client.TimeConversion = conversion;
client.TimeZone = tz;
client.LocalTimeZone = 5.5;
client.Config.TimeConversion = conversion;
client.Config.TimeZone = tz;
client.Config.LocalTimeZone = 5.5;

var result = client.ConvertDate(input.ParseFtpDate(client));

Expand Down
8 changes: 4 additions & 4 deletions FluentFTP.VBExamples/ConnectFTPS.vb
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ Namespace Examples
Friend Module ConnectFTPSExample
Sub ConnectFTPS()
Using conn = New FtpClient("127.0.0.1", "ftptest", "ftptest")
conn.EncryptionMode = FtpEncryptionMode.Explicit
conn.ValidateAnyCertificate = True
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit
conn.Config.ValidateAnyCertificate = True
conn.Connect()
End Using
End Sub
Expand All @@ -18,8 +18,8 @@ Namespace Examples
Dim token = New CancellationToken()

Using conn = New AsyncFtpClient("127.0.0.1", "ftptest", "ftptest")
conn.EncryptionMode = FtpEncryptionMode.Explicit
conn.ValidateAnyCertificate = True
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit
conn.Config.ValidateAnyCertificate = True
Await conn.Connect(token)
End Using
End Function
Expand Down
4 changes: 2 additions & 2 deletions FluentFTP.VBExamples/ConnectFTPSCertificate.vb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Namespace Examples
Friend Module ConnectFTPSCertificateExample
Sub ConnectFTPSCertificate()
Using conn = New FtpClient("127.0.0.1", "ftptest", "ftptest")
conn.EncryptionMode = FtpEncryptionMode.Explicit
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit
AddHandler conn.ValidateCertificate, New FtpSslValidation(AddressOf OnValidateCertificate)
conn.Connect()
End Using
Expand All @@ -18,7 +18,7 @@ Namespace Examples
Dim token = New CancellationToken()

Using conn = New AsyncFtpClient("127.0.0.1", "ftptest", "ftptest")
conn.EncryptionMode = FtpEncryptionMode.Explicit
conn.Config.EncryptionMode = FtpEncryptionMode.Explicit
AddHandler conn.ValidateCertificate, New FtpSslValidation(AddressOf OnValidateCertificate)
Await conn.Connect(token)
End Using
Expand Down
36 changes: 18 additions & 18 deletions FluentFTP/Client/AsyncClient/Connect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,36 +61,36 @@ public partial class AsyncFtpClient {
Status.Reset();

m_hashAlgorithms = FtpHashAlgorithm.NONE;
m_stream.ConnectTimeout = m_connectTimeout;
m_stream.SocketPollInterval = m_socketPollInterval;
m_stream.ConnectTimeout = Config.ConnectTimeout;
m_stream.SocketPollInterval = Config.SocketPollInterval;
await ConnectAsync(m_stream, token);

m_stream.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_keepAlive);
m_stream.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, Config.SocketKeepAlive);

if (EncryptionMode == FtpEncryptionMode.Implicit) {
await m_stream.ActivateEncryptionAsync(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols);
if (Config.EncryptionMode == FtpEncryptionMode.Implicit) {
await m_stream.ActivateEncryptionAsync(Host, Config.ClientCertificates.Count > 0 ? Config.ClientCertificates : null, Config.SslProtocols);
}

await HandshakeAsync(token);
m_serverType = ServerModule.DetectFtpServer(this, HandshakeReply);

if (SendHost) {
if (!(reply = await Execute("HOST " + (SendHostDomain != null ? SendHostDomain : Host), token)).Success) {
if (Config.SendHost) {
if (!(reply = await Execute("HOST " + (Config.SendHostDomain != null ? Config.SendHostDomain : Host), token)).Success) {
throw new FtpException("HOST command failed.");
}
}

// try to upgrade this connection to SSL if supported by the server
if (EncryptionMode == FtpEncryptionMode.Explicit || EncryptionMode == FtpEncryptionMode.Auto) {
if (Config.EncryptionMode == FtpEncryptionMode.Explicit || Config.EncryptionMode == FtpEncryptionMode.Auto) {
reply = await Execute("AUTH TLS", token);
if (!reply.Success) {
Status.ConnectionFTPSFailure = true;
if (EncryptionMode == FtpEncryptionMode.Explicit) {
if (Config.EncryptionMode == FtpEncryptionMode.Explicit) {
throw new FtpSecurityNotAvailableException("AUTH TLS command failed.");
}
}
else if (reply.Success) {
await m_stream.ActivateEncryptionAsync(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols);
await m_stream.ActivateEncryptionAsync(Host, Config.ClientCertificates.Count > 0 ? Config.ClientCertificates : null, Config.SslProtocols);
}
}

Expand All @@ -100,7 +100,7 @@ public partial class AsyncFtpClient {
}

// configure the default FTPS settings
if (IsEncrypted && DataConnectionEncryption) {
if (IsEncrypted && Config.DataConnectionEncryption) {
if (!(reply = await Execute("PBSZ 0", token)).Success) {
throw new FtpCommandException(reply);
}
Expand All @@ -114,11 +114,11 @@ public partial class AsyncFtpClient {
// so save some bandwidth and CPU time and skip executing this again.
// otherwise clear the capabilities in case connection is reused to
// a different server
if (!m_isClone && m_checkCapabilities) {
if (!m_isClone && Config.CheckCapabilities) {
m_capabilities.Clear();
}
bool assumeCaps = false;
if (m_capabilities.IsBlank() && m_checkCapabilities) {
if (m_capabilities.IsBlank() && Config.CheckCapabilities) {
if ((reply = await Execute("FEAT", token)).Success && reply.InfoMessages != null) {
GetFeatures(reply);
}
Expand Down Expand Up @@ -177,15 +177,15 @@ public partial class AsyncFtpClient {
// Unless a custom list parser has been set,
// Detect the listing parser and prefer machine listings over any other type
// FIX : #739 prefer using machine listings to fix issues with GetListing and DeleteDirectory
if (ListingParser != FtpParser.Custom) {
ListingParser = ServerHandler != null ? ServerHandler.GetParser() : FtpParser.Auto;
if (Config.ListingParser != FtpParser.Custom) {
Config.ListingParser = ServerHandler != null ? ServerHandler.GetParser() : FtpParser.Auto;
if (HasFeature(FtpCapability.MLSD)) {
ListingParser = FtpParser.Machine;
Config.ListingParser = FtpParser.Machine;
}
}

// Create the parser even if the auto-OS detection failed
m_listParser.Init(m_serverOS, ListingParser);
CurrentListParser.Init(m_serverOS, Config.ListingParser);

// FIX : #318 always set the type when we create a new connection
ForceSetDataType = true;
Expand All @@ -208,7 +208,7 @@ public partial class AsyncFtpClient {
/// <param name="stream"></param>
/// <param name="token"></param>
protected virtual async Task ConnectAsync(FtpSocketStream stream, CancellationToken token) {
await stream.ConnectAsync(Host, Port, InternetProtocolVersions, token);
await stream.ConnectAsync(Host, Port, Config.InternetProtocolVersions, token);
}
#endif

Expand Down
2 changes: 1 addition & 1 deletion FluentFTP/Client/AsyncClient/Disconnect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public partial class AsyncFtpClient {
public async Task Disconnect(CancellationToken token = default(CancellationToken)) {
if (m_stream != null && m_stream.IsConnected) {
try {
if (DisconnectWithQuit) {
if (Config.DisconnectWithQuit) {
await Execute("QUIT", token);
}
}
Expand Down
2 changes: 1 addition & 1 deletion FluentFTP/Client/AsyncClient/DownloadFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ protected async Task<FtpStatus> DownloadFileToFileAsync(string localPath, string

bool downloadSuccess;
var verified = true;
var attemptsLeft = verifyOptions.HasFlag(FtpVerify.Retry) ? m_retryAttempts : 1;
var attemptsLeft = verifyOptions.HasFlag(FtpVerify.Retry) ? Config.RetryAttempts : 1;
do {

// download the file from the server to a file stream or memory stream
Expand Down
10 changes: 5 additions & 5 deletions FluentFTP/Client/AsyncClient/DownloadFileInternal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,18 @@ protected async Task<bool> DownloadFileInternalAsync(string localPath, string re
}

// open the file for reading
downStream = await OpenRead(remotePath, DownloadDataType, restartPosition, fileLen, token);
downStream = await OpenRead(remotePath, Config.DownloadDataType, restartPosition, fileLen, token);

// if the server has not provided a length for this file or
// if the mode is ASCII or
// if the server is IBM z/OS
// we read until EOF instead of reading a specific number of bytes
var readToEnd = (fileLen <= 0) ||
(DownloadDataType == FtpDataType.ASCII) ||
(Config.DownloadDataType == FtpDataType.ASCII) ||
(ServerHandler != null && ServerHandler.AlwaysReadToEnd(remotePath));

const int rateControlResolution = 100;
var rateLimitBytes = DownloadRateLimit != 0 ? (long)DownloadRateLimit * 1024 : 0;
var rateLimitBytes = Config.DownloadRateLimit != 0 ? (long)Config.DownloadRateLimit * 1024 : 0;
var chunkSize = CalculateTransferChunkSize(rateLimitBytes, rateControlResolution);

// loop till entire file downloaded
Expand All @@ -57,7 +57,7 @@ protected async Task<bool> DownloadFileInternalAsync(string localPath, string re
var anyNoop = false;

// Fix #554: ability to download zero-byte files
if (DownloadZeroByteFiles && outStream == null && localPath != null) {
if (Config.DownloadZeroByteFiles && outStream == null && localPath != null) {
outStream = FtpFileStream.GetFileWriteStream(this, localPath, true, 0, knownFileSize, isAppend, restartPosition);
disposeOutStream = true;
}
Expand Down Expand Up @@ -238,7 +238,7 @@ protected async Task<Tuple<bool, Stream>> ResumeDownloadAsync(string remotePath,
if (ex.IsResumeAllowed()) {
downStream.Dispose();

return Tuple.Create(true, await OpenRead(remotePath, DownloadDataType, offset));
return Tuple.Create(true, await OpenRead(remotePath, Config.DownloadDataType, offset));
}

return Tuple.Create(false, (Stream)null);
Expand Down
8 changes: 4 additions & 4 deletions FluentFTP/Client/AsyncClient/Execute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public partial class AsyncFtpClient {
public async Task<FtpReply> Execute(string command, CancellationToken token) {
FtpReply reply;

if (StaleDataCheck && Status.AllowCheckStaleData) {
if (Config.StaleDataCheck && Status.AllowCheckStaleData) {
#if NETSTANDARD
await ReadStaleData(true, false, true, token);
#else
Expand All @@ -43,11 +43,11 @@ public async Task<FtpReply> Execute(string command, CancellationToken token) {

// hide sensitive data from logs
var commandTxt = command;
if (!LogUserName && command.StartsWith("USER", StringComparison.Ordinal)) {
if (!Config.LogUserName && command.StartsWith("USER", StringComparison.Ordinal)) {
commandTxt = "USER ***";
}

if (!LogPassword && command.StartsWith("PASS", StringComparison.Ordinal)) {
if (!Config.LogPassword && command.StartsWith("PASS", StringComparison.Ordinal)) {
commandTxt = "PASS ***";
}

Expand All @@ -60,7 +60,7 @@ public async Task<FtpReply> Execute(string command, CancellationToken token) {

// send command to FTP server
await m_stream.WriteLineAsync(m_textEncoding, command, token);
m_lastCommandUtc = DateTime.UtcNow;
LastCommandTimestamp = DateTime.UtcNow;
reply = await GetReply(token);

return reply;
Expand Down
6 changes: 3 additions & 3 deletions FluentFTP/Client/AsyncClient/GetListing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ protected async Task<List<string>> GetListingInternal(string listcmd, FtpListOpt
var isUseStat = options.HasFlag(FtpListOption.UseStat);

// always get the file listing in binary to avoid character translation issues with ASCII.
await SetDataTypeNoLockAsync(ListingDataType, token);
await SetDataTypeNoLockAsync(Config.ListingDataType, token);

try {

Expand Down Expand Up @@ -302,9 +302,9 @@ protected async Task<List<string>> GetListingInternal(string listcmd, FtpListOpt
try {
LogLine(FtpTraceLevel.Verbose, "+---------------------------------------+");

if (BulkListing) {
if (Config.BulkListing) {
// increases performance of GetListing by reading multiple lines of the file listing at once
foreach (var line in await stream.ReadAllLinesAsync(Encoding, BulkListingLength, token)) {
foreach (var line in await stream.ReadAllLinesAsync(Encoding, Config.BulkListingLength, token)) {
if (!Strings.IsNullOrWhiteSpace(line)) {
rawlisting.Add(line);
LogLine(FtpTraceLevel.Verbose, "Listing: " + line);
Expand Down
Loading

0 comments on commit bc0cc4c

Please sign in to comment.