Skip to content

Version 4.0.0

Choose a tag to compare

@RuiNelson RuiNelson released this 30 Nov 04:54
· 25 commits to main since this release

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 to SFTPClientProtocol, so every operation goes to a free connection. It replaces multiUpload, multiDownload and multiTune:

    • upload and download send files larger than smallFileThreshold (10 MiB by default) in stripes over every connection, and resume: true continues an interrupted transfer.
    • A broken connection is taken out, replaced, and its stripe is sent again on another one.
    • autoTuneForUpload and autoTuneForDownload add 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 / makePlayerItem stream 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.init is async throws, takes the host without a label, and has a new loginTimeOut. 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 new deinitErrorHandler. Keep close() 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 after close(), stops a debug build at an assertion failure and throws MisuseError in a release build. Impossible values, such as a negative timeout, fail a precondition in every build.

  • Private keys are values - PrivateKey and PublicKey read keys from a file or a string, are LosslessStringConvertible, and report validForSSHAuth. 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 with chacha20-poly1305@openssh.com and 3des-cbc.

  • Host keys as PublicKey values - SFTPClient.getServerPublicKey(_:timeOut:) fetches a server's key, and HostKeyAcceptance has the new .publicKey(_:) and .publicKeys(_:).

  • Shorter ways to connect - TCPLocation reads host, host:port and [ipv6]:port and can be written as a string literal. UserAuthentication can be written as "username:password". SFTPClient also connects from an sftp://user:password@host[:port] URL.

  • Lower latency - TCPLocation has a noDelay property, true by default, that sets TCP_NODELAY. SFTP sends many small requests and waits for each reply, so Nagle's algorithm no longer holds them back. Pass noDelay: false to turn it off.

  • Choose the SSH cipher - cipherPreference takes the ciphers to ask for first in each direction, and cipher reports what was negotiated. OpenSSL's assembly is now used on 64-bit Arm and x86-64 on Apple platforms, Linux and Android, where .aes128GCM is 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:) and pwrite(_:at:) read and write at an offset without moving the file position.

  • Public file conveniences - read(), readAll() and truncate(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 ReferenceCache attached 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: and trapOnDeInitWithoutClose: are replaced by deinitErrorHandler:, and TraceSetToLogger by TraceSetHandler and Trace.
  • 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.
  • UInt64 sizes trap on underflow: compare before computing total - completed on your own values.
  • UserAuthentication, HostKeyAcceptance and TCPLocation values encoded by an earlier version do not decode: UserAuthentication and HostKeyAcceptance (other than .acceptAny) because their cases changed, TCPLocation because of the new noDelay property.
  • 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 smallFileThreshold bytes in place over one connection, and a striped upload needs a server that accepts SETSTAT to 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, upload and download, and replace login, fork(loggedIn:) and contentsOfDirectory.