Repository navigation
Version 4.0.0
SwiftSFTP 4.0 changes how the library reports problems, how objects are released, how you log in and how files are transferred over several connections. Most programs need a few mechanical edits, and the compiler finds nearly all of them: start with the 3.24 to 4.0 migration guide.
What's New
-
SFTPSwarm: several connections used as one client - A swarm keeps a set of connections to one server open and conforms toSFTPClientProtocol, so every operation goes to a free connection. It replacesmultiUpload,multiDownloadandmultiTune:uploadanddownloadsend files larger thansmallFileThreshold(10 MiB by default) in stripes over every connection, andresume: truecontinues an interrupted transfer.- A broken connection is taken out, replaced, and its stripe is sent again on another one.
autoTuneForUploadandautoTuneForDownloadadd connections for as long as that makes a transfer faster, and return the throughput measured for each connection count.- A swarm shares one block-level cache across its connections, and
makeAsset/makePlayerItemstream over all of them.
let swarm = try await SFTPSwarm(client, numberOfForksToCreate: 3) try await swarm.upload(from: localFile, to: remotePath, resume: true) { _, _, _, _ in true }
-
The initializer logs in - A client that exists is connected, authenticated and ready.
SFTPClient.initisasync throws, takes the host without a label, and has a newloginTimeOut.SFTPClient.preflightConfigurationCheck(_:hostKeyAcceptance:authentication:)validates a configuration without connecting. -
Closing is optional - A client, file or shell agent that is released without
close()closes itself, and releasing never blocks. Failures during that teardown go to the newdeinitErrorHandler. Keepclose()where the outcome matters, for example before renaming a file you just wrote. -
Clearer failures - A server rejecting your credentials throws
UserAuthenticationError. Misuse, such as using a client afterclose(), stops a debug build at an assertion failure and throwsMisuseErrorin a release build. Impossible values, such as a negative timeout, fail a precondition in every build. -
Private keys are values -
PrivateKeyandPublicKeyread keys from a file or a string, areLosslessStringConvertible, and reportvalidForSSHAuth. Authenticate with.privateKey(_:)or.privateKeys(_:). Errors in a key (missing file, malformed data, wrong passphrase) now surface where you create it, not at login.PrivateKey(string:passphrase:)also reads OpenSSH keys encrypted withchacha20-poly1305@openssh.comand3des-cbc. -
Host keys as
PublicKeyvalues -SFTPClient.getServerPublicKey(_:timeOut:)fetches a server's key, andHostKeyAcceptancehas the new.publicKey(_:)and.publicKeys(_:). -
Shorter ways to connect -
TCPLocationreadshost,host:portand[ipv6]:portand can be written as a string literal.UserAuthenticationcan be written as"username:password".SFTPClientalso connects from ansftp://user:password@host[:port]URL. -
Lower latency -
TCPLocationhas anoDelayproperty,trueby default, that setsTCP_NODELAY. SFTP sends many small requests and waits for each reply, so Nagle's algorithm no longer holds them back. PassnoDelay: falseto turn it off. -
Choose the SSH cipher -
cipherPreferencetakes the ciphers to ask for first in each direction, andcipherreports what was negotiated. OpenSSL's assembly is now used on 64-bit Arm and x86-64 on Apple platforms, Linux and Android, where.aes128GCMis faster and lighter on the CPU than libssh2's default ChaCha20-Poly1305. See SSH cipher.let client = try await SFTPClient( "sftp.example.com", authentication: authentication, cipherPreference: (clientToServer: [.aes128GCM], serverToClient: [.aes128GCM]) )
-
Faster
read()-read()without an argument now reads as much as the client keeps in flight (readAhead, 2 MiB by default) instead of a fixed 32 KiB, so one call fills the pipeline. -
Positional I/O -
pread(upTo:at:)andpwrite(_:at:)read and write at an offset without moving the file position. -
Public file conveniences -
read(),readAll()andtruncate(toSize:)on file handles are public. -
Static Linux SDK - SwiftSFTP builds with Swift's Static Linux SDK (musl).
Bug Fixes
- Fixed a hang, with memory growing until the process died, when a client with a
ReferenceCacheattached used a relative path that starts with.., such as../file. It appeared with PathWorks 2.1.0.
Migration Guide
The 3.24 to 4.0 migration guide lists every change with a replacement and a checklist. In short:
Requirements
- Minimum platforms rise to macOS 12, iOS 15, tvOS 15, watchOS 9 and Mac Catalyst 15. visionOS, Android (API 28), Linux and Windows are unchanged.
- swift-log is no longer a dependency, and SwiftSFTP logs nothing.
logger:andtrapOnDeInitWithoutClose:are replaced bydeinitErrorHandler:, andTraceSetToLoggerbyTraceSetHandlerandTrace. - PathWorks 2.1.0 or later is required.
API changes
| 3.24 | 4.0 |
|---|---|
SFTPClient(openSocketIn:...) then login(timeOut:), or initAndLogin(...) |
try await SFTPClient(...) |
fork(loggedIn:) |
fork() |
AlreadyClosed, NotLoggedIn |
MisuseError (release builds); an assertion failure in debug builds |
SFTPClientInvalidConfig.authenticationFailed(_:) |
UserAuthenticationError |
PrivateKeySet, PrivateKeyString, PrivateKeyFile, .privateKeyFile, .privateKeyString |
PrivateKey with .privateKey(_:) / .privateKeys(_:) |
isValid_... and isValidForSSH_... checks on key text |
PrivateKey / PublicKey and validForSSHAuth |
AsymmetricKeyType, a key's type |
AsymmetricAlgorithm types, a key's algorithm |
SwiftSFTP_Curve25519, OpenSSHKeyPair |
AsymmetricCryptography.EdDSA.Ed25519 |
getServerHostKey(openSocketIn:timeOut:shortHandForm:) |
getServerHostKey(_:timeOut:), or getServerPublicKey(_:timeOut:) for the key alone |
.shortHandAcceptedKeys, .loadFromFile, .loadFromFileString |
.publicKeys, .loadKnownHostsFile, .loadKnownHostsString |
contentsOfDirectory(path:recursive:) and the Set-returning listDirectory |
listDirectory(path:recursive:), returning [FileMetadata] |
File sizes and offsets as Int64 |
FileSize and FileOffset (UInt64) |
multiUpload, multiDownload, multiTune, ResumeBehavior |
SFTPSwarm |
makeAsset(at:readAheadSize:stripeSize:), makePlayerItem(at:...) |
await makeAsset(path:readAhead:bufferSize:), await makePlayerItem(path:...) |
ReferenceCache.close() |
Release the cache, or call removeAll() |
Before:
let client = try SFTPClient(openSocketIn: location, operationsTimeOut: 30, authentication: auth)
try await client.login(timeOut: 15)
defer { try? await client.close() }After:
let client = try await SFTPClient(location, authentication: auth, loginTimeOut: 15, operationsTimeOut: 30)Behaviour changes to check
- Invalid timeouts, keepalive intervals, buffer sizes, non-
file://URLs and empty shell agent inputs now stop the process instead of throwing. Validate values that come from user input first. UInt64sizes trap on underflow: compare before computingtotal - completedon your own values.UserAuthentication,HostKeyAcceptanceandTCPLocationvalues encoded by an earlier version do not decode:UserAuthenticationandHostKeyAcceptance(other than.acceptAny) because their cases changed,TCPLocationbecause of the newnoDelayproperty.- Partial files left by 3.x multi-connection transfers are not resumed: the next striped transfer deletes them and starts from zero.
- A swarm moves files of up to
smallFileThresholdbytes in place over one connection, and a striped upload needs a server that acceptsSETSTATto shorten a file. - A striped transfer to a destination that another striped transfer is writing throws
FileTransferErrors.transferAlreadyInProgress(path:).
Custom SFTPClientProtocol conformers must also:
- make the initializer
async throws, with the new parameters (loginTimeOut,cipherPreference,deinitErrorHandler) in the order the protocol declares; - add
preflightConfigurationCheck,getServerPublicKey,cipher,uploadanddownload, and replacelogin,fork(loggedIn:)andcontentsOfDirectory.