Bundle: redb-route / redb.Route.Sftp (redb.Route.Sftp.txt), 13 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Sftp/Extensions/ServiceCollectionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Sftp;
///
/// Extension methods for registering the SFTP transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// sftp:// URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteSftp();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteSftp(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Sftp/Fluent/SftpDsl.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/Fluent/SftpDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.Sftp;
///
/// Fluent API for SFTP endpoints.
///
/// .From(Sftp.Directory("/incoming").Host("sftp.example.com").Username("admin").Password("secret")
/// .Include("*.csv").Recursive().Delete())
/// .To(Sftp.Directory("/outgoing").Host("sftp.example.com").Username("admin").Password("secret")
/// .AutoCreate())
///
///
public static class Sftp
{
/// Creates an SFTP endpoint for the given remote directory path.
public static SftpBuilder Directory(string remotePath) => new(remotePath);
}
///
/// Fluent builder for SFTP endpoint URIs.
///
public sealed class SftpBuilder
{
private readonly string _remotePath;
// Connection
private string? _host;
private string? _port;
private string? _username;
private string? _password;
private string? _connectionFactory;
private string? _privateKeyPath;
private string? _privateKeyPassphrase;
private bool _useKeyboardInteractive;
private string? _preferredAuthentications;
private string? _serverFingerprint;
private bool _strictHostKeyChecking;
private string? _knownHostsFile;
private string? _connectionTimeout;
private string? _operationTimeout;
private string? _keepAliveInterval;
private string? _bufferSize;
private bool _compression;
// Proxy
private string? _proxyType;
private string? _proxyHost;
private string? _proxyPort;
private string? _proxyUsername;
private string? _proxyPassword;
// Reconnection
private string? _maximumReconnectAttempts;
private string? _reconnectDelay;
private bool _disconnect;
// Consumer
private string? _delay;
private string? _initialDelay;
private string? _include;
private string? _exclude;
private string? _antInclude;
private string? _antExclude;
private bool? _antFilterCaseSensitive;
private string? _filterDirectory;
private string? _filterFile;
private string? _filter;
private bool _recursive;
private string? _maxDepth;
private string? _minDepth;
private string? _sortBy;
private string? _maxMessagesPerPoll;
private string? _backoffMultiplier;
private string? _backoffIdleThreshold;
private string? _backoffErrorThreshold;
private bool _backoffOnFailedExchanges;
private string? _minAge;
private string? _maxAge;
// Post-processing
private bool _noop;
private bool _delete;
private string? _moveTo;
private string? _moveExisting;
private string? _preMove;
private string? _moveFailed;
// Idempotency
private bool _idempotent;
private string? _idempotentKey;
private string? _doneFileName;
// Transfer
private bool _streamBody;
private string? _charset;
private string? _separator;
private bool _ignoreFileNotFoundOrPermissionError;
private bool? _startingDirectoryMustExist;
private bool _directoryMustExist;
private bool _sendEmptyMessageWhenIdle;
// Producer
private string? _fileName;
private string? _fileExist;
private string? _moveExistingFileStrategy;
private string? _tempPrefix;
private string? _tempFileName;
private string? _chmod;
private string? _chmodDirectory;
private bool? _autoCreate;
private bool _allowNullBody;
private bool? _eagerDeleteTargetFile;
private bool _keepLastModified;
private bool _flatten;
private bool? _jailStartingDirectory;
private string? _appendChars;
internal SftpBuilder(string remotePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(remotePath);
_remotePath = remotePath;
}
// ── Connection ────────────────────────────────────────────────────
/// SFTP server hostname. Default "localhost".
public SftpBuilder Host(IExpression host) { _host = host.ToTemplateString(); return this; }
/// SFTP server hostname (template string, supports ${...}).
public SftpBuilder Host(string host) { _host = host; return this; }
/// SFTP server port. Default 22.
public SftpBuilder Port(int port) { _port = port.ToString(); return this; }
/// SFTP server port from an expression.
public SftpBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; }
/// Username for authentication.
public SftpBuilder Username(IExpression username) { _username = username.ToTemplateString(); return this; }
/// Username for authentication (template string, supports ${...}).
public SftpBuilder Username(string username) { _username = username; return this; }
/// Password for authentication.
public SftpBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; }
/// Password for authentication (template string, supports ${...}).
public SftpBuilder Password(string password) { _password = password; return this; }
///
/// References a named from the route registry instead of
/// putting the password / key passphrase / proxy password in the URI.
///
public SftpBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Path to private key file.
public SftpBuilder PrivateKey(IExpression path, IExpression? passphrase = null)
{
_privateKeyPath = path.ToTemplateString(); _privateKeyPassphrase = passphrase?.ToTemplateString(); return this;
}
/// Enable keyboard-interactive authentication.
public SftpBuilder UseKeyboardInteractive() { _useKeyboardInteractive = true; return this; }
/// Preferred authentication methods, comma-separated.
public SftpBuilder PreferredAuthentications(string methods) { _preferredAuthentications = methods; return this; }
/// Expected server host key fingerprint.
public SftpBuilder ServerFingerprint(IExpression fingerprint) { _serverFingerprint = fingerprint.ToTemplateString(); return this; }
/// Expected server host key fingerprint (template string, supports ${...}).
public SftpBuilder ServerFingerprint(string fingerprint) { _serverFingerprint = fingerprint; return this; }
/// Enable strict host key checking.
public SftpBuilder StrictHostKeyChecking() { _strictHostKeyChecking = true; return this; }
/// Path to known_hosts file.
public SftpBuilder KnownHostsFile(string path) { _knownHostsFile = path; return this; }
/// Connection timeout in milliseconds. Default 30000.
public SftpBuilder ConnectionTimeout(int ms) { _connectionTimeout = ms.ToString(); return this; }
/// Connection timeout from an expression.
public SftpBuilder ConnectionTimeout(IExpression ms) { _connectionTimeout = ms.ToTemplateString(); return this; }
/// Operation timeout in milliseconds. Default 60000.
public SftpBuilder OperationTimeout(int ms) { _operationTimeout = ms.ToString(); return this; }
/// Operation timeout from an expression.
public SftpBuilder OperationTimeout(IExpression ms) { _operationTimeout = ms.ToTemplateString(); return this; }
/// Keep-alive interval in milliseconds. 0 = disabled.
public SftpBuilder KeepAliveInterval(int ms) { _keepAliveInterval = ms.ToString(); return this; }
/// Keep-alive interval from an expression.
public SftpBuilder KeepAliveInterval(IExpression ms) { _keepAliveInterval = ms.ToTemplateString(); return this; }
/// Buffer size for transfers. Default 32768.
public SftpBuilder BufferSize(int bytes) { _bufferSize = bytes.ToString(); return this; }
/// Buffer size from an expression.
public SftpBuilder BufferSize(IExpression bytes) { _bufferSize = bytes.ToTemplateString(); return this; }
/// Enable SSH compression.
public SftpBuilder Compression() { _compression = true; return this; }
// ── Proxy ─────────────────────────────────────────────────────────
/// Proxy configuration: type (None, Socks4, Socks5, Http), host, and port.
public SftpBuilder Proxy(string type, IExpression host, int port = 1080)
{
_proxyType = type; _proxyHost = host.ToTemplateString(); _proxyPort = port.ToString(); return this;
}
/// Proxy authentication.
public SftpBuilder ProxyAuth(IExpression username, IExpression password)
{
_proxyUsername = username.ToTemplateString(); _proxyPassword = password.ToTemplateString(); return this;
}
// ── Reconnection ──────────────────────────────────────────────────
/// Maximum reconnect attempts. Default 3.
public SftpBuilder MaximumReconnectAttempts(int attempts) { _maximumReconnectAttempts = attempts.ToString(); return this; }
/// Maximum reconnect attempts from an expression.
public SftpBuilder MaximumReconnectAttempts(IExpression attempts) { _maximumReconnectAttempts = attempts.ToTemplateString(); return this; }
/// Reconnect delay in milliseconds. Default 1000.
public SftpBuilder ReconnectDelay(int ms) { _reconnectDelay = ms.ToString(); return this; }
/// Reconnect delay from an expression.
public SftpBuilder ReconnectDelay(IExpression ms) { _reconnectDelay = ms.ToTemplateString(); return this; }
/// Disconnect after each operation.
public SftpBuilder Disconnect() { _disconnect = true; return this; }
// ── Consumer ──────────────────────────────────────────────────────
/// Poll delay in milliseconds. Default 60000.
public SftpBuilder Delay(int ms) { _delay = ms.ToString(); return this; }
/// Poll delay from an expression.
public SftpBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; }
/// Initial delay before first poll. Default 1000.
public SftpBuilder InitialDelay(int ms) { _initialDelay = ms.ToString(); return this; }
/// Initial delay from an expression.
public SftpBuilder InitialDelay(IExpression ms) { _initialDelay = ms.ToTemplateString(); return this; }
/// Skip this many polls once a backoff threshold is hit (0 = disabled; needs a threshold).
public SftpBuilder BackoffMultiplier(int value) { _backoffMultiplier = value.ToString(); return this; }
/// Backoff multiplier from an expression.
public SftpBuilder BackoffMultiplier(IExpression value) { _backoffMultiplier = value.ToTemplateString(); return this; }
/// Consecutive idle polls (no exchange created) that arm the backoff skip (0 = disabled).
public SftpBuilder BackoffIdleThreshold(int value) { _backoffIdleThreshold = value.ToString(); return this; }
/// Backoff idle threshold from an expression.
public SftpBuilder BackoffIdleThreshold(IExpression value) { _backoffIdleThreshold = value.ToTemplateString(); return this; }
/// Consecutive failed polls (the poll itself threw) that arm the backoff skip (0 = disabled).
public SftpBuilder BackoffErrorThreshold(int value) { _backoffErrorThreshold = value.ToString(); return this; }
/// Backoff error threshold from an expression.
public SftpBuilder BackoffErrorThreshold(IExpression value) { _backoffErrorThreshold = value.ToTemplateString(); return this; }
/// Count a poll whose every created exchange failed as an error for backoff (needs BackoffErrorThreshold).
public SftpBuilder BackoffOnFailedExchanges() { _backoffOnFailedExchanges = true; return this; }
/// File name pattern to include (e.g. "*.csv").
public SftpBuilder Include(string pattern) { _include = pattern; return this; }
/// File name pattern to exclude.
public SftpBuilder Exclude(string pattern) { _exclude = pattern; return this; }
/// Ant-style patterns over the path relative to the polled directory, several separated by commas ("TYPE_A/outbox/*.csv"). Sees directories, which Include does not.
public SftpBuilder AntInclude(string patterns) { _antInclude = patterns; return this; }
/// Ant-style patterns over the relative path that drop a file ("archive/**").
public SftpBuilder AntExclude(string patterns) { _antExclude = patterns; return this; }
/// Whether the Ant patterns respect case (default true).
public SftpBuilder AntFilterCaseSensitive(bool value = true) { _antFilterCaseSensitive = value; return this; }
/// Condition deciding whether a subdirectory is walked into at all — evaluated before it is listed.
public SftpBuilder FilterDirectory(string condition) { _filterDirectory = condition; return this; }
/// Condition deciding whether a polled file is taken, evaluated before it is read or moved.
public SftpBuilder FilterFile(string condition) { _filterFile = condition; return this; }
/// Name of an IGenericFileFilter in the route registry ("#myFilter") deciding for files and directories.
public SftpBuilder Filter(string registryName) { _filter = registryName; return this; }
/// Recurse into subdirectories.
public SftpBuilder Recursive() { _recursive = true; return this; }
/// Maximum recursion depth. 0 = unlimited.
public SftpBuilder MaxDepth(int depth) { _maxDepth = depth.ToString(); return this; }
/// Maximum recursion depth from an expression.
public SftpBuilder MaxDepth(IExpression depth) { _maxDepth = depth.ToTemplateString(); return this; }
/// Minimum recursion depth before yielding files.
public SftpBuilder MinDepth(int depth) { _minDepth = depth.ToString(); return this; }
/// Minimum recursion depth from an expression.
public SftpBuilder MinDepth(IExpression depth) { _minDepth = depth.ToTemplateString(); return this; }
/// Sort order: None, Name, NameDesc, Modified, ModifiedDesc, Size, SizeDesc.
public SftpBuilder SortBy(string sort) { _sortBy = sort; return this; }
/// Max files per poll. 0 = unlimited.
public SftpBuilder MaxMessagesPerPoll(int max) { _maxMessagesPerPoll = max.ToString(); return this; }
/// Max files per poll from an expression.
public SftpBuilder MaxMessagesPerPoll(IExpression max) { _maxMessagesPerPoll = max.ToTemplateString(); return this; }
/// Minimum file age in milliseconds before processing.
public SftpBuilder MinAge(long ms) { _minAge = ms.ToString(); return this; }
/// Minimum file age from an expression.
public SftpBuilder MinAge(IExpression ms) { _minAge = ms.ToTemplateString(); return this; }
/// Maximum file age in milliseconds.
public SftpBuilder MaxAge(long ms) { _maxAge = ms.ToString(); return this; }
/// Maximum file age from an expression.
public SftpBuilder MaxAge(IExpression ms) { _maxAge = ms.ToTemplateString(); return this; }
// ── Post-processing ───────────────────────────────────────────────
/// Do nothing after processing (leave file in place).
public SftpBuilder Noop() { _noop = true; return this; }
/// Delete file after processing.
public SftpBuilder Delete() { _delete = true; return this; }
/// Move processed file to this directory.
public SftpBuilder MoveTo(IExpression directory) { _moveTo = directory.ToTemplateString(); return this; }
/// Move processed file to this directory (template string, supports ${...}).
public SftpBuilder MoveTo(string directory) { _moveTo = directory; return this; }
/// Strategy when file exists in move target: Override, Append, Fail, Ignore, Move, TryRename.
public SftpBuilder MoveExisting(string strategy) { _moveExisting = strategy; return this; }
/// Pre-move directory (temporary move before processing).
public SftpBuilder PreMove(IExpression directory) { _preMove = directory.ToTemplateString(); return this; }
/// Pre-move directory (template string, supports ${...}).
public SftpBuilder PreMove(string directory) { _preMove = directory; return this; }
/// Directory for files that failed processing.
public SftpBuilder MoveFailed(IExpression directory) { _moveFailed = directory.ToTemplateString(); return this; }
/// Directory for files that failed processing (template string, supports ${...}).
public SftpBuilder MoveFailed(string directory) { _moveFailed = directory; return this; }
// ── Idempotency ───────────────────────────────────────────────────
/// Enable idempotent consumer with optional key expression.
public SftpBuilder Idempotent(IExpression? key = null) { _idempotent = true; _idempotentKey = key?.ToTemplateString(); return this; }
/// Enable idempotent consumer with a key (template string, supports ${...}).
public SftpBuilder Idempotent(string key) { _idempotent = true; _idempotentKey = key; return this; }
/// Done file name pattern.
public SftpBuilder DoneFileName(IExpression name) { _doneFileName = name.ToTemplateString(); return this; }
/// Done file name pattern (template string, supports ${...}).
public SftpBuilder DoneFileName(string name) { _doneFileName = name; return this; }
// ── Transfer ──────────────────────────────────────────────────────
/// Set exchange body to SftpFileStream instead of byte[] (consumer only).
public SftpBuilder StreamBody() { _streamBody = true; return this; }
/// Character encoding for text mode. Default "utf-8".
public SftpBuilder Charset(string charset) { _charset = charset; return this; }
/// Input path normalization: Auto (backslashes become "/") or Unix (byte-for-byte).
public SftpBuilder Separator(string sep) { _separator = sep; return this; }
/// Ignore file-not-found or permission errors.
public SftpBuilder IgnoreFileNotFoundOrPermissionError() { _ignoreFileNotFoundOrPermissionError = true; return this; }
/// Starting directory must exist. Default true.
public SftpBuilder StartingDirectoryMustExist(bool must = true) { _startingDirectoryMustExist = must; return this; }
/// Target directory must exist (producer).
public SftpBuilder DirectoryMustExist() { _directoryMustExist = true; return this; }
/// Send empty message when poll finds no files.
public SftpBuilder SendEmptyMessageWhenIdle() { _sendEmptyMessageWhenIdle = true; return this; }
// ── Producer ──────────────────────────────────────────────────────
/// Output file name or expression (e.g. Header("CamelFileName")).
public SftpBuilder FileName(IExpression name) { _fileName = name.ToTemplateString(); return this; }
/// Output file name (template string, supports ${...}).
public SftpBuilder FileName(string name) { _fileName = name; return this; }
/// Strategy when target file exists: Override, Append, Fail, Ignore, Move, TryRename.
public SftpBuilder FileExist(string strategy) { _fileExist = strategy; return this; }
/// Strategy for moving existing files: Backup, Timestamp, Guid.
public SftpBuilder MoveExistingFileStrategy(string strategy) { _moveExistingFileStrategy = strategy; return this; }
/// Temporary file prefix during write.
public SftpBuilder TempPrefix(IExpression prefix) { _tempPrefix = prefix.ToTemplateString(); return this; }
/// Temporary file prefix during write (template string, supports ${...}).
public SftpBuilder TempPrefix(string prefix) { _tempPrefix = prefix; return this; }
/// Temporary file name during write.
public SftpBuilder TempFileName(IExpression name) { _tempFileName = name.ToTemplateString(); return this; }
/// Temporary file name during write (template string, supports ${...}).
public SftpBuilder TempFileName(string name) { _tempFileName = name; return this; }
/// File permissions (e.g. "644").
public SftpBuilder Chmod(string permissions) { _chmod = permissions; return this; }
/// Directory permissions (e.g. "755").
public SftpBuilder ChmodDirectory(string permissions) { _chmodDirectory = permissions; return this; }
/// Auto-create target directory. Default true.
public SftpBuilder AutoCreate(bool autoCreate = true) { _autoCreate = autoCreate; return this; }
/// Allow sending null body.
public SftpBuilder AllowNullBody() { _allowNullBody = true; return this; }
/// Eagerly delete target file before writing. Default true.
public SftpBuilder EagerDeleteTargetFile(bool eager = true) { _eagerDeleteTargetFile = eager; return this; }
/// Preserve last modified timestamp.
public SftpBuilder KeepLastModified() { _keepLastModified = true; return this; }
/// Flatten directory structure (single directory).
public SftpBuilder Flatten() { _flatten = true; return this; }
/// Jail operations within the starting directory. Default true.
public SftpBuilder JailStartingDirectory(bool jail = true) { _jailStartingDirectory = jail; return this; }
/// Characters to append after writing.
public SftpBuilder AppendChars(string chars) { _appendChars = chars; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the SFTP endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("sftp:///");
sb.Append(_remotePath.TrimStart('/'));
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (!string.IsNullOrEmpty(value)) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value)
{
if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant());
}
// Connection
AppendIf("host", _host);
AppendIf("port", _port);
AppendIf("username", _username);
AppendIf("password", _password);
AppendIf("connectionFactory", _connectionFactory);
AppendIf("privateKeyPath", _privateKeyPath);
AppendIf("privateKeyPassphrase", _privateKeyPassphrase);
AppendBool("useKeyboardInteractive", _useKeyboardInteractive);
AppendIf("preferredAuthentications", _preferredAuthentications);
AppendIf("serverFingerprint", _serverFingerprint);
AppendBool("strictHostKeyChecking", _strictHostKeyChecking);
AppendIf("knownHostsFile", _knownHostsFile);
AppendIf("connectionTimeout", _connectionTimeout);
AppendIf("operationTimeout", _operationTimeout);
AppendIf("keepAliveInterval", _keepAliveInterval);
AppendIf("bufferSize", _bufferSize);
AppendBool("compression", _compression);
// Proxy
AppendIf("proxyType", _proxyType);
AppendIf("proxyHost", _proxyHost);
AppendIf("proxyPort", _proxyPort);
AppendIf("proxyUsername", _proxyUsername);
AppendIf("proxyPassword", _proxyPassword);
// Reconnection
AppendIf("maximumReconnectAttempts", _maximumReconnectAttempts);
AppendIf("reconnectDelay", _reconnectDelay);
AppendBool("disconnect", _disconnect);
// Consumer
AppendIf("delay", _delay);
AppendIf("initialDelay", _initialDelay);
AppendIf("include", _include);
AppendIf("exclude", _exclude);
AppendIf("antInclude", _antInclude);
AppendIf("antExclude", _antExclude);
if (_antFilterCaseSensitive is { } cs) AppendIf("antFilterCaseSensitive", cs ? "true" : "false");
AppendIf("filterDirectory", _filterDirectory);
AppendIf("filterFile", _filterFile);
AppendIf("filter", _filter);
AppendBool("recursive", _recursive);
AppendIf("maxDepth", _maxDepth);
AppendIf("minDepth", _minDepth);
AppendIf("sortBy", _sortBy);
AppendIf("maxMessagesPerPoll", _maxMessagesPerPoll);
AppendIf("backoffMultiplier", _backoffMultiplier);
AppendIf("backoffIdleThreshold", _backoffIdleThreshold);
AppendIf("backoffErrorThreshold", _backoffErrorThreshold);
AppendBool("backoffOnFailedExchanges", _backoffOnFailedExchanges);
AppendIf("minAge", _minAge);
AppendIf("maxAge", _maxAge);
// Post-processing
AppendBool("noop", _noop);
AppendBool("delete", _delete);
AppendIf("moveTo", _moveTo);
AppendIf("moveExisting", _moveExisting);
AppendIf("preMove", _preMove);
AppendIf("moveFailed", _moveFailed);
// Idempotency
AppendBool("idempotent", _idempotent);
AppendIf("idempotentKey", _idempotentKey);
AppendIf("doneFileName", _doneFileName);
// Transfer
AppendBool("streamBody", _streamBody);
AppendIf("charset", _charset);
AppendIf("separator", _separator);
AppendBool("ignoreFileNotFoundOrPermissionError", _ignoreFileNotFoundOrPermissionError);
AppendBoolExplicit("startingDirectoryMustExist", _startingDirectoryMustExist);
AppendBool("directoryMustExist", _directoryMustExist);
AppendBool("sendEmptyMessageWhenIdle", _sendEmptyMessageWhenIdle);
// Producer
AppendIf("fileName", _fileName);
AppendIf("fileExist", _fileExist);
AppendIf("moveExistingFileStrategy", _moveExistingFileStrategy);
AppendIf("tempPrefix", _tempPrefix);
AppendIf("tempFileName", _tempFileName);
AppendIf("chmod", _chmod);
AppendIf("chmodDirectory", _chmodDirectory);
AppendBoolExplicit("autoCreate", _autoCreate);
AppendBool("allowNullBody", _allowNullBody);
AppendBoolExplicit("eagerDeleteTargetFile", _eagerDeleteTargetFile);
AppendBool("keepLastModified", _keepLastModified);
AppendBool("flatten", _flatten);
AppendBoolExplicit("jailStartingDirectory", _jailStartingDirectory);
AppendIf("appendChars", _appendChars);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(SftpBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Sftp/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/README.md
----
# redb.Route.Sftp
> Documentation and articles:
SFTP transport for redb.Route. Polling consumer and atomic producer via SSH.NET — key/password auth, proxy, idempotency, glob filtering, temp-file upload, chmod, and recursive directory traversal.
[](https://www.nuget.org/packages/redb.Route.Sftp)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.Sftp
```
## Usage
### Fluent DSL
```csharp
using redb.Route.Sftp;
// Poll remote directory
From(Sftp.Directory("/uploads")
.Host("sftp.example.com").Port(22)
.Username("user").PrivateKey(Constant("/keys/id_rsa"))
.Include("*.xml")
.Delay(10000)
.MoveTo("/uploads/archive")
.Recursive()
.Idempotent())
.Log("Downloaded: ${header.CamelFileName}")
.To("direct://process");
// Upload files atomically
From("direct://export")
.To(Sftp.Directory("/outgoing")
.Host("sftp.example.com")
.Username("user").Password("secret")
.TempPrefix(".uploading-")
.Chmod("0644")
.AutoCreate());
// With proxy
From(Sftp.Directory("/data")
.Host("internal-sftp")
.Username("svc")
.Proxy("Http", Constant("proxy.corp.net"), 8080)
.ProxyAuth(Constant("proxy-user"), Constant("proxy-pass")))
.To("direct://ingest");
```
## Fluent Builder API
| Category | Methods |
|----------|---------|
| **Connection** | `.Host()`, `.Port()`, `.Username()`, `.Password()`, `.PrivateKey()`, `.UseKeyboardInteractive()`, `.PreferredAuthentications()`, `.ServerFingerprint()`, `.StrictHostKeyChecking()`, `.KnownHostsFile()`, `.ConnectionTimeout()`, `.OperationTimeout()`, `.KeepAliveInterval()`, `.BufferSize()`, `.Compression()` |
| **Proxy** | `.Proxy(type, host, port)`, `.ProxyAuth(user, pass)` |
| **Reconnect** | `.MaximumReconnectAttempts()`, `.ReconnectDelay()`, `.Disconnect()` |
| **Consumer** | `.Delay()`, `.InitialDelay()`, `.Include()`, `.Exclude()`, `.Recursive()`, `.MaxDepth()`, `.MinDepth()`, `.SortBy()`, `.MaxMessagesPerPoll()`, `.MinAge()`, `.MaxAge()` |
| **Path filters** | `.AntInclude()`, `.AntExclude()`, `.AntFilterCaseSensitive()`, `.FilterDirectory()`, `.FilterFile()`, `.Filter()` — see [the base package](../redb.Route.GenericFile/README.md#path-filters); this is how one session polls named directories out of a partner tree instead of one route per directory |
| **Poll backoff** | `.BackoffMultiplier()`, `.BackoffIdleThreshold()`, `.BackoffErrorThreshold()`, `.BackoffOnFailedExchanges()` |
| **Post-process** | `.Noop()`, `.Delete()`, `.MoveTo()`, `.MoveExisting()`, `.PreMove()`, `.MoveFailed()` |
| **Idempotency** | `.Idempotent()`, `.DoneFileName()` |
| **Transfer** | `.Charset()`, `.Separator()` |
| **Producer** | `.FileExist()`, `.TempPrefix()`, `.TempFileName()`, `.Chmod()`, `.ChmodDirectory()`, `.AutoCreate()`, `.AllowNullBody()`, `.EagerDeleteTargetFile()`, `.KeepLastModified()`, `.Flatten()`, `.JailStartingDirectory()`, `.AppendChars()` |
> Most builder methods accept both constant values and `IExpression` for runtime resolution via the expression engine.
## Part of
[redb.Route](../README.md) — ESB & EIP Framework for .NET
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new SftpConnectionFactory
{
Host = "sftp.partner.com",
Username = "exchange",
PrivateKeyPath = "/secrets/id_ed25519",
});
// sftp://outbox?connectionFactory=prod
```
## Tracing
As every connector built on `redb.Route.GenericFile` (see the `redb.Route.File` README): a root `Consumer` span,
`file read sftp`, per routed file, none for an empty poll, an error when the route fails; a `Producer` span per upload,
`file write sftp`, an error when it fails. `RouteEngineOptions.EnableTelemetry = false` opens neither.
Path: redb-route/redb.Route.Sftp/SftpClientFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpClientFactory.cs
----
using Renci.SshNet;
namespace redb.Route.Sftp;
///
/// Factory for creating configured instances from endpoint options.
/// Handles authentication methods (password, public key, keyboard-interactive), proxy tunneling,
/// host key verification, timeouts, keep-alive, and buffer sizes.
///
internal static class SftpClientFactory
{
///
/// Creates and configures an ready for connecting.
/// The caller is responsible for connecting, disconnecting, and disposing the client.
///
public static SftpClient Create(SftpEndpointOptions options)
{
ArgumentNullException.ThrowIfNull(options);
var authMethods = BuildAuthenticationMethods(options);
if (authMethods.Length == 0)
throw new InvalidOperationException(
"No authentication method configured. Provide Password or PrivateKeyPath.");
var connInfo = BuildConnectionInfo(options, authMethods);
// compression=true: prefer zlib@openssh.com in the negotiation, keeping the remaining
// algorithms as fallback so a server without compression still connects. Declared and
// documented from day one, wired to nothing until the options sweep.
if (options.Compression)
{
var existing = connInfo.CompressionAlgorithms.Where(kv => kv.Key != "zlib@openssh.com").ToList();
connInfo.CompressionAlgorithms.Clear();
connInfo.CompressionAlgorithms["zlib@openssh.com"] = () => new Renci.SshNet.Compression.ZlibOpenSsh();
foreach (var kv in existing)
connInfo.CompressionAlgorithms[kv.Key] = kv.Value;
}
var client = new SftpClient(connInfo);
client.OperationTimeout = TimeSpan.FromMilliseconds(options.OperationTimeout);
client.BufferSize = (uint)options.BufferSize;
if (options.KeepAliveInterval > 0)
{
client.KeepAliveInterval = TimeSpan.FromMilliseconds(options.KeepAliveInterval);
}
ConfigureHostKeyValidation(client, options);
return client;
}
private static AuthenticationMethod[] BuildAuthenticationMethods(SftpEndpointOptions options)
{
var methods = new List();
// Public key authentication
if (!string.IsNullOrEmpty(options.PrivateKeyPath))
{
var keyFile = string.IsNullOrEmpty(options.PrivateKeyPassphrase)
? new PrivateKeyFile(options.PrivateKeyPath)
: new PrivateKeyFile(options.PrivateKeyPath, options.PrivateKeyPassphrase);
methods.Add(new PrivateKeyAuthenticationMethod(options.Username, keyFile));
}
// Password authentication
if (!string.IsNullOrEmpty(options.Password))
{
methods.Add(new PasswordAuthenticationMethod(options.Username, options.Password));
}
// Keyboard-interactive (2FA, PAM prompts)
if (options.UseKeyboardInteractive)
{
var kia = new KeyboardInteractiveAuthenticationMethod(options.Username);
var password = options.Password ?? "";
kia.AuthenticationPrompt += (_, e) =>
{
foreach (var prompt in e.Prompts)
{
prompt.Response = password;
}
};
methods.Add(kia);
}
return methods.ToArray();
}
private static ConnectionInfo BuildConnectionInfo(SftpEndpointOptions options, AuthenticationMethod[] authMethods)
{
ConnectionInfo connInfo;
if (options.ProxyType != SftpProxyType.None && !string.IsNullOrEmpty(options.ProxyHost))
{
var proxyType = options.ProxyType switch
{
SftpProxyType.Socks4 => ProxyTypes.Socks4,
SftpProxyType.Socks5 => ProxyTypes.Socks5,
SftpProxyType.Http => ProxyTypes.Http,
_ => ProxyTypes.None
};
connInfo = new ConnectionInfo(
options.Host, options.Port, options.Username,
proxyType, options.ProxyHost, options.ProxyPort,
options.ProxyUsername, options.ProxyPassword,
authMethods);
}
else
{
connInfo = new ConnectionInfo(options.Host, options.Port, options.Username, authMethods);
}
connInfo.Timeout = TimeSpan.FromMilliseconds(options.ConnectionTimeout);
return connInfo;
}
private static void ConfigureHostKeyValidation(SftpClient client, SftpEndpointOptions options)
{
if (!options.StrictHostKeyChecking)
{
// Accept all host keys (common in dev/test environments)
client.HostKeyReceived += (_, e) => e.CanTrust = true;
}
else if (!string.IsNullOrEmpty(options.ServerFingerprint))
{
// Validate against a known fingerprint
var expected = options.ServerFingerprint.Replace(":", "").Replace("-", "");
client.HostKeyReceived += (_, e) =>
{
var actual = BitConverter.ToString(e.FingerPrint).Replace("-", "");
e.CanTrust = string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase);
};
}
// If StrictHostKeyChecking=true but no fingerprint/known_hosts, SSH.NET's default behavior applies
// (may reject unknown hosts depending on version)
}
}
Path: redb-route/redb.Route.Sftp/SftpComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpComponent.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
using redb.Route.GenericFile;
namespace redb.Route.Sftp;
///
/// SFTP transport component for redb.Route.
/// Scheme: sftp.
///
/// URI format: sftp:///remote/path?host=server&port=22&username=admin&password=secret
///
///
/// Provides enterprise-grade SFTP integration powered by SSH.NET:
/// polling consumer with glob filtering, idempotency, pre/post-move;
/// atomic producer with temp-file upload, chmod, and auto-create directories.
/// Supports password, public-key, and keyboard-interactive authentication plus proxy tunneling.
///
///
public sealed class SftpComponent : ComponentBase
{
///
public override string Scheme => "sftp";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new SftpEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.ResolveFilter(Context);
// Named ConnectionFactory keeps the password / key passphrase / proxy password
// out of the route URI.
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
// A set-but-unknown name fails loud -- never a silent fallback to URI params.
var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory);
factory.ApplyTo(options, uri);
}
options.Validate();
return new SftpEndpoint(uri, this, options);
}
}
///
/// SFTP endpoint. Creates either a consumer (for polling a remote directory)
/// or a producer (for uploading files). The path part of the URI is the remote base directory.
///
public sealed class SftpEndpoint : EndpointBase
{
/// Creates an SFTP endpoint.
public SftpEndpoint(EndpointUri uri, SftpComponent component, SftpEndpointOptions options)
: base(uri, component, options)
{
}
/// The remote base directory path derived from the endpoint URI.
public string RemotePath => NormalizeRemotePath(Uri.Path);
/// Gets the endpoint options for external access.
internal SftpEndpointOptions EndpointOptions => Options;
///
public override IProducer CreateProducer()
{
return new SftpProducer(this, Options, new SftpFileOperations(Options));
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new SftpConsumer(this, processor, Options, new SftpFileOperations(Options));
}
private static string NormalizeRemotePath(string path)
{
// Ensure leading slash for absolute SFTP paths
if (string.IsNullOrEmpty(path))
return "/";
// Normalize double slashes
while (path.Contains("//"))
path = path.Replace("//", "/");
// Ensure leading slash
if (!path.StartsWith('/'))
path = "/" + path;
// Remove trailing slash (unless root)
if (path.Length > 1 && path.EndsWith('/'))
path = path[..^1];
return path;
}
}
Path: redb-route/redb.Route.Sftp/SftpConnectionFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpConnectionFactory.cs
----
using redb.Route.Abstractions;
using redb.Route.GenericFile;
using redb.Route.Core;
namespace redb.Route.Sftp;
///
/// Named connection factory for SFTP. Register it in the route registry and reference it by name
/// from the endpoint URI (connectionFactory=my-sftp) so the password, private-key
/// passphrase and proxy password never have to appear in the URI, and therefore can never reach
/// logs, telemetry, or the dashboard.
///
/// Example:
///
/// context.AddToRegistry("partner-sftp", new SftpConnectionFactory
/// {
/// Host = "sftp.partner.com", Port = 22, Username = "svc-drop",
/// PrivateKeyPath = "/etc/redb/keys/partner.pem",
/// PrivateKeyPassphrase = Environment.GetEnvironmentVariable("SFTP_PASSPHRASE")!
/// });
///
/// r.From("sftp://inbox?connectionFactory=partner-sftp") // no secrets in the route
///
///
///
public sealed class SftpConnectionFactory : RemoteFileConnectionFactory
{
/// Path to the private key file.
public string PrivateKeyPath { get; set; } = "";
/// Passphrase protecting the private key.
[Sensitive]
public string PrivateKeyPassphrase { get; set; } = "";
/// Preferred authentication methods, comma-separated.
public string PreferredAuthentications { get; set; } = "";
/// Expected server host-key fingerprint.
public string ServerFingerprint { get; set; } = "";
/// Enforce known-hosts checking.
public bool StrictHostKeyChecking { get; set; }
/// Path to the known_hosts file.
public string KnownHostsFile { get; set; } = "";
/// Proxy host, when connecting through a proxy.
public string ProxyHost { get; set; } = "";
/// Proxy port.
public int ProxyPort { get; set; } = 1080;
/// Proxy username.
public string ProxyUsername { get; set; } = "";
/// Proxy password.
[Sensitive]
public string ProxyPassword { get; set; } = "";
///
internal override void ApplyTo(RemoteFileEndpointOptions options, EndpointUri uri)
{
base.ApplyTo(options, uri);
if (options is not SftpEndpointOptions sftp) return;
var supplied = uri.RawParameters;
if (!supplied.ContainsKey(nameof(sftp.PrivateKeyPath))) sftp.PrivateKeyPath = PrivateKeyPath;
if (!supplied.ContainsKey(nameof(sftp.PrivateKeyPassphrase)))
sftp.PrivateKeyPassphrase = PrivateKeyPassphrase;
if (!supplied.ContainsKey(nameof(sftp.PreferredAuthentications)))
sftp.PreferredAuthentications = PreferredAuthentications;
if (!supplied.ContainsKey(nameof(sftp.ServerFingerprint)))
sftp.ServerFingerprint = ServerFingerprint;
if (!supplied.ContainsKey(nameof(sftp.StrictHostKeyChecking)))
sftp.StrictHostKeyChecking = StrictHostKeyChecking;
if (!supplied.ContainsKey(nameof(sftp.KnownHostsFile))) sftp.KnownHostsFile = KnownHostsFile;
if (!supplied.ContainsKey(nameof(sftp.ProxyHost))) sftp.ProxyHost = ProxyHost;
if (!supplied.ContainsKey(nameof(sftp.ProxyPort))) sftp.ProxyPort = ProxyPort;
if (!supplied.ContainsKey(nameof(sftp.ProxyUsername))) sftp.ProxyUsername = ProxyUsername;
if (!supplied.ContainsKey(nameof(sftp.ProxyPassword))) sftp.ProxyPassword = ProxyPassword;
}
}
Path: redb-route/redb.Route.Sftp/SftpConsumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpConsumer.cs
----
using redb.Route.Abstractions;
using redb.Route.GenericFile;
namespace redb.Route.Sftp;
///
/// SFTP consumer. Polls a remote directory at regular intervals via SSH.NET,
/// applies glob filters, idempotency, pre/post-move, and processes each file via the route processor.
/// After successful processing, applies the configured post-processing strategy (noop/delete/move).
/// Supports recursive directory scanning, min/max age filtering, done-file markers,
/// and automatic reconnection.
///
public sealed class SftpConsumer : RemoteFileConsumer
{
private readonly SftpEndpoint _endpoint;
///
protected override string BasePath => _endpoint.RemotePath;
///
protected override string ConsumerName => $"sftp:{Options.Host}:{Options.Port}{_endpoint.Uri.Path}";
/// Creates an SFTP consumer.
internal SftpConsumer(SftpEndpoint endpoint, IProcessor processor, SftpEndpointOptions options, SftpFileOperations operations)
: base(endpoint, processor, options, operations)
{
_endpoint = endpoint;
}
///
protected override void SetExchangeHeaders(IMessage message, GenericFileInfo file, string workPath)
{
var relativePath = Operations.GetRelativePath(file.BasePath, workPath);
var parentDir = Operations.GetParentPath(workPath);
message.Headers[SftpHeaders.FileName] = file.Name;
message.Headers[SftpHeaders.FileNameOnly] = Operations.GetFileNameWithoutExtension(file.Name);
message.Headers[SftpHeaders.FileExtension] = Operations.GetExtension(file.Name);
message.Headers[SftpHeaders.RemotePath] = workPath;
message.Headers[SftpHeaders.RelativePath] = relativePath;
message.Headers[SftpHeaders.RemoteParent] = parentDir;
message.Headers[SftpHeaders.FileLength] = file.Length;
message.Headers[SftpHeaders.FileLastModified] = file.LastModified;
message.Headers[SftpHeaders.Host] = Options.Host;
message.Headers[SftpHeaders.Port] = Options.Port;
message.Headers[SftpHeaders.Username] = Options.Username;
// SFTP-specific: POSIX owner/group from Extras
if (file.Extras != null)
{
if (file.Extras.TryGetValue("UserId", out var uid))
message.Headers[SftpHeaders.FileOwner] = uid;
if (file.Extras.TryGetValue("GroupId", out var gid))
message.Headers[SftpHeaders.FileGroup] = gid;
}
}
}
Path: redb-route/redb.Route.Sftp/SftpEndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpEndpointOptions.cs
----
using redb.Route.Core;
using redb.Route.GenericFile;
namespace redb.Route.Sftp;
///
/// Endpoint options for SFTP transport. All properties are auto-bound from URI query parameters.
///
/// URI format: sftp:///remote/path?host=server&port=22&username=admin&password=secret&...
///
///
/// Inherits shared polling, post-processing, idempotency, and producer options from
/// . Adds SFTP-specific: SSH authentication,
/// proxy tunneling, chmod, flatten, jail, and more.
///
///
public class SftpEndpointOptions : RemoteFileEndpointOptions
{
/// Creates SFTP endpoint options with protocol-specific defaults.
public SftpEndpointOptions()
{
Delay = 60_000;
InitialDelay = 1000;
StartingDirectoryMustExist = true;
}
// ═══════════════════════════════════════════════════════════════════
// CONNECTION: SFTP-specific
// ═══════════════════════════════════════════════════════════════════
/// SFTP server port. (default: 22)
public override int Port { get; set; } = 22;
///
/// Path to a PEM/OpenSSH private key file for public-key authentication.
/// Supports RSA, DSA, ECDSA, ED25519 keys.
///
public string PrivateKeyPath { get; set; } = "";
/// Passphrase for the encrypted private key (if applicable).
[Sensitive]
public string PrivateKeyPassphrase { get; set; } = "";
///
/// Enable keyboard-interactive authentication in addition to password/key.
/// Useful for 2FA or custom PAM prompts. The password is sent as the response. (default: false)
///
public bool UseKeyboardInteractive { get; set; }
///
/// Preferred authentication order. Comma-separated: "publickey,password,keyboard-interactive".
/// Empty = SSH.NET default (try all configured methods).
///
public string PreferredAuthentications { get; set; } = "";
///
/// Expected server host key fingerprint (MD5 hex, colon-separated, e.g. "AA:BB:CC:...").
/// If set and StrictHostKeyChecking is true, the connection is rejected on mismatch.
///
public string ServerFingerprint { get; set; } = "";
///
/// If true, validate the server's host key against .
/// If false (default), all host keys are accepted. (default: false)
///
public bool StrictHostKeyChecking { get; set; }
///
/// Path to a known_hosts file (OpenSSH format) for host key verification.
/// Used only when is true and ServerFingerprint is empty.
///
public string KnownHostsFile { get; set; } = "";
///
/// SSH keep-alive interval in milliseconds. 0 = disabled.
/// Sends SSH_MSG_IGNORE packets to prevent firewall/NAT timeouts. (default: 0)
///
public int KeepAliveInterval { get; set; }
/// SSH.NET internal buffer size in bytes. (default: 32768 = 32 KB)
public int BufferSize { get; set; } = 32_768;
/// Enable zlib compression on the SSH channel. (default: false)
public bool Compression { get; set; }
// ── Proxy ────────────────────────────────────────────────────────
/// Proxy type for tunneling the SSH connection. (default: None)
public SftpProxyType ProxyType { get; set; } = SftpProxyType.None;
/// Proxy hostname or IP.
public string ProxyHost { get; set; } = "";
/// Proxy port. (default: 1080)
public int ProxyPort { get; set; } = 1080;
/// Proxy username (for SOCKS5 or HTTP proxy auth).
public string ProxyUsername { get; set; } = "";
/// Proxy password.
[Sensitive]
public string ProxyPassword { get; set; } = "";
// ═══════════════════════════════════════════════════════════════════
// TRANSFER OPTIONS (SFTP-specific)
// ═══════════════════════════════════════════════════════════════════
// Binary and StepWise are gone (the options sweep): both were declared and read by
// nothing, and neither CAN mean anything here. SFTP has no text mode - the protocol moves raw
// bytes, full stop. And it has no change-directory operation either (SSH_FXP_* requests carry
// paths; a client-side "cd" is bookkeeping), so the FTP notion of step-wise navigation does
// not map - directory creation already walks segment by segment unconditionally.
///
/// Input normalization for remote paths: Auto (default) converts backslashes in configured
/// paths and file names to "/", Unix takes them byte-for-byte. The wire separator is always
/// "/" — that is the SFTP protocol, there is no Windows mode.
///
public SftpSeparator Separator { get; set; } = SftpSeparator.Auto;
///
/// If true, silently ignore FileNotFoundException or permission errors during listing.
/// Useful when the directory may not exist yet. (default: false)
///
public bool IgnoreFileNotFoundOrPermissionError { get; set; }
///
/// If true, each subdirectory must exist when using recursive mode.
/// If false, silently skip missing subdirectories. (default: false)
///
public bool DirectoryMustExist { get; set; }
// ═══════════════════════════════════════════════════════════════════
// PRODUCER: SFTP-specific
// ═══════════════════════════════════════════════════════════════════
///
/// Strategy for moving existing files when FileExist=Move. (default: Timestamp)
///
public SftpMoveExistingStrategy MoveExistingFileStrategy { get; set; } = SftpMoveExistingStrategy.Timestamp;
///
/// Set POSIX file permissions after upload (octal string, e.g. "0644").
/// Empty = do not change permissions. Requires server support.
///
public string Chmod { get; set; } = "";
///
/// Set POSIX permissions on auto-created directories (octal string, e.g. "0755").
/// Empty = server default.
///
public string ChmodDirectory { get; set; } = "";
///
/// If true, preserve the CamelFileLastModified header as the remote file's modification time.
/// Requires SFTP v3+ set-stat support. (default: false)
///
public bool KeepLastModified { get; set; }
///
/// If true, flatten nested directory structures — all files are uploaded to the base directory.
/// File names from subdirectories lose their directory prefix. (default: false)
///
public bool Flatten { get; set; }
///
/// If true, prevent the producer from writing outside the base directory.
/// FileName expressions that navigate with ".." are rejected. (default: true)
///
public bool JailStartingDirectory { get; set; } = true;
// ═══════════════════════════════════════════════════════════════════
// VALIDATION
// ═══════════════════════════════════════════════════════════════════
///
public override void Validate()
{
ValidateRemote();
if (string.IsNullOrWhiteSpace(Username))
throw new ArgumentException("SFTP Username must be specified.");
if (string.IsNullOrEmpty(Password) && string.IsNullOrEmpty(PrivateKeyPath))
throw new ArgumentException("At least one authentication method required: provide Password or PrivateKeyPath.");
if (BufferSize < 1024)
throw new ArgumentOutOfRangeException(nameof(BufferSize), BufferSize,
"BufferSize must be at least 1024 bytes.");
if (ProxyType != SftpProxyType.None && string.IsNullOrWhiteSpace(ProxyHost))
throw new ArgumentException("ProxyHost must be specified when ProxyType is not None.");
if (ProxyPort is < 1 or > 65535)
throw new ArgumentOutOfRangeException(nameof(ProxyPort), ProxyPort, "ProxyPort must be 1–65535.");
if (!string.IsNullOrEmpty(Chmod) && !IsValidOctalPermissions(Chmod))
throw new ArgumentException($"Chmod must be a valid octal permission string (e.g. '0644'), got: '{Chmod}'");
if (!string.IsNullOrEmpty(ChmodDirectory) && !IsValidOctalPermissions(ChmodDirectory))
throw new ArgumentException($"ChmodDirectory must be a valid octal permission string (e.g. '0755'), got: '{ChmodDirectory}'");
}
///
/// Parses an octal permissions string (e.g. "0644") to a short value for SFTP chmod.
///
internal static short ParseOctalPermissions(string octal)
{
return Convert.ToInt16(octal, 8);
}
private static bool IsValidOctalPermissions(string value)
{
if (string.IsNullOrEmpty(value)) return false;
try
{
var v = Convert.ToInt32(value, 8);
return v is >= 0 and <= 0x1FF; // 0000 to 0777
}
catch
{
return false;
}
}
}
Path: redb-route/redb.Route.Sftp/SftpEnums.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpEnums.cs
----
namespace redb.Route.Sftp;
///
/// SOCKS/HTTP proxy types for tunneling SSH connections through corporate proxies.
/// Maps directly to SSH.NET's ProxyTypes enum.
///
public enum SftpProxyType
{
/// No proxy — direct connection.
None,
/// SOCKS4 proxy.
Socks4,
/// SOCKS5 proxy (supports username/password authentication).
Socks5,
/// HTTP CONNECT proxy.
Http
}
///
/// Strategy for moving the existing file at the producer target path before upload.
/// Used when is selected.
///
public enum SftpMoveExistingStrategy
{
/// Rename to {name}.bak (overwrite previous backup).
Backup,
/// Rename with timestamp suffix: {name}.yyyyMMddHHmmssfff
Timestamp,
/// Rename with GUID suffix: {name}.{guid}
Guid
}
///
/// Path separator mode for SFTP remote paths.
///
public enum SftpSeparator
{
/// Default: joins with "/" and additionally normalizes backslashes in the inputs.
Auto,
/// Strict Unix forward-slash: inputs are joined with "/" byte-for-byte.
Unix
// No Windows member: the SFTP protocol defines "/" as the path separator (SSH_FXP requests
// carry canonical paths; servers on Windows accept "/" too). A backslash mode could never be
// honest - the jail check, mkdir splitting, and recursive listing all speak "/" - so it was
// removed the same way Binary/StepWise were.
}
Path: redb-route/redb.Route.Sftp/SftpFileOperations.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpFileOperations.cs
----
using System.Text;
using Renci.SshNet;
using Renci.SshNet.Sftp;
using redb.Route.GenericFile;
namespace redb.Route.Sftp;
///
/// Implements for SFTP via SSH.NET.
/// Manages lifecycle through Connect/Disconnect.
/// All path operations use forward-slash UNIX convention.
///
internal sealed class SftpFileOperations : IRemoteFileOperations
{
private readonly SftpEndpointOptions _options;
private SftpClient? _client;
/// Creates SFTP file operations for the given endpoint options.
public SftpFileOperations(SftpEndpointOptions options)
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
}
/// The underlying SSH.NET SFTP client (null until connected).
internal SftpClient? Client => _client;
// ═══════════════════════════════════════════════════════════════════
// CONNECTION LIFECYCLE
// ═══════════════════════════════════════════════════════════════════
///
public bool IsConnected => _client is { IsConnected: true };
///
public Task ConnectAsync(CancellationToken ct = default)
{
if (_client != null)
{
if (_client.IsConnected) _client.Disconnect();
_client.Dispose();
_client = null;
}
_client = SftpClientFactory.Create(_options);
_client.Connect();
return Task.CompletedTask;
}
///
public Task DisconnectAsync(CancellationToken ct = default)
{
if (_client != null)
{
try
{
if (_client.IsConnected)
_client.Disconnect();
}
finally
{
_client.Dispose();
_client = null;
}
}
return Task.CompletedTask;
}
// ═══════════════════════════════════════════════════════════════════
// ENUMERATION
// ═══════════════════════════════════════════════════════════════════
///
public Task> ListFilesAsync(
string directory, bool recursive, int maxDepth, int minDepth,
Func? directoryFilter = null,
CancellationToken ct = default)
{
var client = RequireClient();
var result = EnumerateFiles(client, directory, directory, 0, recursive, maxDepth, minDepth, directoryFilter);
return Task.FromResult(result);
}
private List EnumerateFiles(
SftpClient client, string dirPath, string basePath,
int depth, bool recursive, int maxDepth, int minDepth,
Func? directoryFilter)
{
var result = new List();
IEnumerable entries;
try
{
entries = client.ListDirectory(dirPath);
}
catch (Exception) when (_options.IgnoreFileNotFoundOrPermissionError)
{
return result;
}
foreach (var entry in entries)
{
if (entry.Name is "." or "..")
continue;
if (entry.IsDirectory)
{
if (recursive && (maxDepth == 0 || depth < maxDepth))
{
var subPath = CombinePath(dirPath, entry.Name);
// Asked before the descent: a directory turned down here costs no listing,
// which is the point of filterDirectory on a tree of partner directories.
if (directoryFilter != null && !directoryFilter(subPath, GetRelativePath(basePath, subPath)))
continue;
try
{
result.AddRange(EnumerateFiles(client, subPath, basePath, depth + 1, recursive, maxDepth, minDepth, directoryFilter));
}
catch (Renci.SshNet.Common.SftpPathNotFoundException)
when (!_options.DirectoryMustExist && !client.Exists(subPath))
{
// The subdirectory vanished between the parent listing and the descent
// (another process consumed it). directoryMustExist=false (default): skip;
// true: let it escape - the poll reports the inconsistency.
// The Exists probe keeps this a TOCTOU guard and nothing more: a directory
// that still exists means the path was built wrong - that must escape,
// not become a silent per-poll skip.
}
}
}
else if (entry.IsRegularFile)
{
if (minDepth > 0 && depth < minDepth)
continue;
result.Add(new GenericFileInfo
{
Name = entry.Name,
FullPath = entry.FullName,
BasePath = basePath,
Length = entry.Length,
LastModified = new DateTimeOffset(entry.LastWriteTime.ToUniversalTime(), TimeSpan.Zero),
Depth = depth,
Extras = new Dictionary
{
["UserId"] = entry.UserId,
["GroupId"] = entry.GroupId
}
});
}
}
return result;
}
// ═══════════════════════════════════════════════════════════════════
// READ
// ═══════════════════════════════════════════════════════════════════
///
public Task ReadAllBytesAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
using var ms = new MemoryStream();
client.DownloadFile(path, ms);
return Task.FromResult(ms.ToArray());
}
///
public Task OpenReadAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
Stream stream = client.OpenRead(path);
return Task.FromResult(stream);
}
// ═══════════════════════════════════════════════════════════════════
// WRITE
// ═══════════════════════════════════════════════════════════════════
///
public Task WriteAsync(string path, byte[] data, CancellationToken ct = default)
{
var client = RequireClient();
using var ms = new MemoryStream(data);
client.UploadFile(ms, path);
return Task.CompletedTask;
}
///
public async Task WriteAsync(string path, Stream data, CancellationToken ct = default)
{
var client = RequireClient();
// Copy to MemoryStream first to ensure seekability
using var ms = new MemoryStream();
await data.CopyToAsync(ms, ct).ConfigureAwait(false);
ms.Position = 0;
client.UploadFile(ms, path);
}
///
public Task AppendAsync(string path, byte[] data, CancellationToken ct = default)
{
var client = RequireClient();
var encoding = ResolveEncoding();
using var writer = client.AppendText(path, encoding);
writer.Write(encoding.GetString(data));
writer.Flush();
return Task.CompletedTask;
}
///
public Task AppendTextAsync(string path, string text, Encoding encoding, CancellationToken ct = default)
{
var client = RequireClient();
using var writer = client.AppendText(path, encoding);
writer.Write(text);
writer.Flush();
return Task.CompletedTask;
}
// ═══════════════════════════════════════════════════════════════════
// FILE OPERATIONS
// ═══════════════════════════════════════════════════════════════════
///
public Task ExistsAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
return Task.FromResult(client.Exists(path));
}
///
public Task DeleteAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
client.DeleteFile(path);
return Task.CompletedTask;
}
///
public Task MoveAsync(string source, string destination, bool overwrite, CancellationToken ct = default)
{
var client = RequireClient();
if (overwrite && client.Exists(destination))
{
client.DeleteFile(destination);
}
client.RenameFile(source, destination);
return Task.CompletedTask;
}
// ═══════════════════════════════════════════════════════════════════
// DIRECTORY OPERATIONS
// ═══════════════════════════════════════════════════════════════════
///
public Task CreateDirectoryAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
EnsureRemoteDirectoryExists(client, path);
return Task.CompletedTask;
}
///
public Task DirectoryExistsAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
return Task.FromResult(client.Exists(path));
}
///
/// Recursively creates all directories in the given path.
///
internal static void EnsureRemoteDirectoryExists(SftpClient client, string path)
{
if (client.Exists(path))
return;
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
var current = "";
foreach (var part in parts)
{
current += "/" + part;
if (!client.Exists(current))
{
client.CreateDirectory(current);
}
}
}
// ═══════════════════════════════════════════════════════════════════
// PATH HELPERS
// ═══════════════════════════════════════════════════════════════════
// The SFTP protocol's one true separator. The separator option only controls whether the
// INPUTS are normalized (Auto) or taken byte-for-byte (Unix) - see SftpSeparator.
private const char Sep = '/';
///
public string CombinePath(string basePath, string relativePath)
{
if (_options.Separator == SftpSeparator.Auto)
{
basePath = basePath?.Replace('\\', '/') ?? "";
relativePath = relativePath?.Replace('\\', '/') ?? "";
}
if (string.IsNullOrEmpty(basePath)) return Sep + relativePath;
if (string.IsNullOrEmpty(relativePath)) return basePath;
return basePath.TrimEnd(Sep) + Sep + relativePath.TrimStart(Sep);
}
///
public string GetParentPath(string path)
{
var lastSlash = path.LastIndexOf(Sep);
return lastSlash <= 0 ? Sep.ToString() : path[..lastSlash];
}
///
public string GetFileName(string path)
{
var lastSlash = path.LastIndexOf(Sep);
return lastSlash >= 0 ? path[(lastSlash + 1)..] : path;
}
///
public string GetFileNameWithoutExtension(string name)
{
var fileName = GetFileName(name);
var dotIndex = fileName.LastIndexOf('.');
return dotIndex > 0 ? fileName[..dotIndex] : fileName;
}
///
public string GetExtension(string name)
{
var fileName = GetFileName(name);
var dotIndex = fileName.LastIndexOf('.');
return dotIndex >= 0 ? fileName[dotIndex..] : "";
}
///
public string GetRelativePath(string basePath, string fullPath)
{
if (fullPath.StartsWith(basePath, StringComparison.Ordinal))
{
var relative = fullPath[basePath.Length..].TrimStart('/');
return string.IsNullOrEmpty(relative) ? fullPath : relative;
}
return fullPath;
}
///
public bool IsAbsolutePath(string path)
{
return path.StartsWith('/');
}
// ═══════════════════════════════════════════════════════════════════
// SFTP-SPECIFIC HELPERS
// ═══════════════════════════════════════════════════════════════════
///
/// Applies POSIX chmod to a file or directory.
///
internal void ApplyChmod(string path, string octalPermissions)
{
var client = RequireClient();
var mode = SftpEndpointOptions.ParseOctalPermissions(octalPermissions);
var attrs = client.GetAttributes(path);
attrs.SetPermissions(mode);
client.SetAttributes(path, attrs);
}
///
/// Gets file attributes from the remote server.
///
internal SftpFileAttributes GetAttributes(string path)
{
var client = RequireClient();
return client.GetAttributes(path);
}
///
/// Sets file attributes on the remote server.
///
internal void SetAttributes(string path, SftpFileAttributes attrs)
{
var client = RequireClient();
client.SetAttributes(path, attrs);
}
// ═══════════════════════════════════════════════════════════════════
// INTERNALS
// ═══════════════════════════════════════════════════════════════════
private SftpClient RequireClient()
{
return _client ?? throw new InvalidOperationException(
"SFTP client is not connected. Call ConnectAsync() first.");
}
private Encoding ResolveEncoding()
{
try
{
return Encoding.GetEncoding(_options.Charset);
}
catch
{
return Encoding.UTF8;
}
}
}
Path: redb-route/redb.Route.Sftp/SftpHeaders.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpHeaders.cs
----
namespace redb.Route.Sftp;
///
/// Constants for exchange headers set by the SFTP component.
/// All prefixed with "redbSftp." to avoid collisions with other components.
///
public static class SftpHeaders
{
/// Common prefix for all SFTP component headers.
public const string Prefix = "redbSftp.";
// ── Headers set on the In message by the consumer ────────────────
/// Full file name with extension (e.g. "report.csv").
public const string FileName = "redbSftp.Name";
/// File name without the extension (e.g. "report").
public const string FileNameOnly = "redbSftp.NameOnly";
/// File extension including the dot (e.g. ".csv").
public const string FileExtension = "redbSftp.Extension";
/// Full remote path on the SFTP server (e.g. "/upload/report.csv").
public const string RemotePath = "redbSftp.RemotePath";
/// Path relative to the polling base directory.
public const string RelativePath = "redbSftp.RelativePath";
/// Parent directory on the remote server.
public const string RemoteParent = "redbSftp.RemoteParent";
/// File size in bytes.
public const string FileLength = "redbSftp.Length";
/// Last modified date/time as DateTimeOffset (UTC).
public const string FileLastModified = "redbSftp.LastModified";
/// File permissions (octal string, e.g. "0644").
public const string FilePermissions = "redbSftp.Permissions";
/// File owner UID.
public const string FileOwner = "redbSftp.Owner";
/// File group GID.
public const string FileGroup = "redbSftp.Group";
/// SFTP server host that the file was retrieved from.
public const string Host = "redbSftp.Host";
/// SFTP server port.
public const string Port = "redbSftp.Port";
/// Username used for the SFTP connection.
public const string Username = "redbSftp.Username";
// ── Headers set by the producer after uploading ──────────────────
/// Full remote path of the file that was actually written by the producer.
public const string FileNameProduced = "redbSftp.NameProduced";
}
Path: redb-route/redb.Route.Sftp/SftpProducer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/SftpProducer.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.GenericFile;
namespace redb.Route.Sftp;
///
/// SFTP producer. Uploads exchange body to a remote file on the SFTP server.
/// Supports atomic upload via temp files (TempPrefix/TempFileName → rename),
/// multiple file-exist strategies, dynamic file names via expressions, chmod,
/// automatic directory creation, and jail-path validation.
///
public sealed class SftpProducer : RemoteFileProducer
{
private readonly SftpEndpoint _endpoint;
private readonly SftpFileOperations _sftpOps;
///
protected override string BasePath => _endpoint.RemotePath;
///
protected override string FileNameProducedHeader => SftpHeaders.FileNameProduced;
/// Creates an SFTP producer.
internal SftpProducer(SftpEndpoint endpoint, SftpEndpointOptions options, SftpFileOperations operations)
: base(endpoint, options, operations)
{
_endpoint = endpoint;
_sftpOps = operations;
}
///
protected override string ResolveTargetPath(IExchange exchange)
{
string fileName;
if (Options.FileName != null)
{
fileName = Options.FileName.Value.Resolve(exchange) ?? "output";
}
else
{
// Try to get filename from incoming exchange headers (SFTP-specific first)
var headerFileName = exchange.In.Headers.TryGetValue(SftpHeaders.FileName, out var hfn)
? hfn?.ToString()
: null;
// Fallback to generic file header
if (string.IsNullOrEmpty(headerFileName))
{
headerFileName = exchange.In.Headers.TryGetValue("redbFile.Name", out var ffn)
? ffn?.ToString()
: null;
}
fileName = headerFileName ?? $"redb-{Guid.NewGuid():N}";
}
if (Options.Flatten)
{
var lastSlash = fileName.LastIndexOf('/');
if (lastSlash >= 0)
fileName = fileName[(lastSlash + 1)..];
}
return Operations.CombinePath(BasePath, fileName);
}
///
protected override void ValidatePath(string targetPath)
{
if (!Options.JailStartingDirectory)
return;
var normalizedTarget = NormalizePath(targetPath);
if (!GenericFileUtils.IsWithinDirectory(BasePath, normalizedTarget, '/', StringComparison.Ordinal))
{
throw new InvalidOperationException(
$"Producer path '{targetPath}' escapes the jail directory '{BasePath}'. " +
"Set JailStartingDirectory=false to allow writing outside the base directory.");
}
}
///
protected override async Task BeforeWriteAsync(string targetDir, CancellationToken ct)
{
await base.BeforeWriteAsync(targetDir, ct).ConfigureAwait(false);
// Apply directory chmod if configured
if (Options.AutoCreate && !string.IsNullOrEmpty(Options.ChmodDirectory))
{
try
{
_sftpOps.ApplyChmod(targetDir, Options.ChmodDirectory);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "SFTP: chmod {Permissions} failed for directory {Path}",
Options.ChmodDirectory, targetDir);
}
}
}
///
protected override Task AfterWriteAsync(IExchange exchange, string targetPath, CancellationToken ct)
{
// Apply file chmod if configured
if (!string.IsNullOrEmpty(Options.Chmod))
{
try
{
_sftpOps.ApplyChmod(targetPath, Options.Chmod);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "SFTP: chmod {Permissions} failed for {Path}",
Options.Chmod, targetPath);
}
}
// Preserve last modified time if requested
if (Options.KeepLastModified &&
exchange.In.Headers.TryGetValue(SftpHeaders.FileLastModified, out var lastModObj) &&
lastModObj is DateTimeOffset lastMod)
{
try
{
var attrs = _sftpOps.GetAttributes(targetPath);
attrs.LastWriteTime = lastMod.UtcDateTime;
_sftpOps.SetAttributes(targetPath, attrs);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "SFTP: failed to preserve LastModified for {Path}", targetPath);
}
}
return Task.CompletedTask;
}
///
protected override async Task MoveExistingFile(string path, CancellationToken ct)
{
var suffix = Options.MoveExistingFileStrategy switch
{
SftpMoveExistingStrategy.Backup => ".bak",
SftpMoveExistingStrategy.Timestamp => "." + DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmssfff"),
SftpMoveExistingStrategy.Guid => "." + Guid.NewGuid().ToString("N"),
_ => "." + DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmssfff")
};
var backupPath = path + suffix;
await Operations.MoveAsync(path, backupPath, false, ct).ConfigureAwait(false);
}
// ── Helpers ──────────────────────────────────────────────────────
private static string NormalizePath(string path)
{
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
var stack = new Stack();
foreach (var part in parts)
{
if (part == "..")
{
if (stack.Count > 0) stack.Pop();
}
else if (part != ".")
{
stack.Push(part);
}
}
return "/" + string.Join("/", stack.Reverse());
}
}
Path: redb-route/redb.Route.Sftp/redb.Route.Sftp.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sftp/redb.Route.Sftp.csproj
----
redb.Route.Sftp
SFTP transport for redb.Route ESB framework. Polling consumer and atomic producer with SSH.NET — key/password auth, proxy, idempotency, glob filtering, temp-file upload, chmod, recursive directories.
esb;messaging;sftp;ssh;file-transfer;polling;redb
README.md