QFtpCompat 1.0.0
Qt6-compatible async FTP client library
Loading...
Searching...
No Matches
QFtpCompat Class Reference

Asynchronous FTP client for Qt6. More...

#include <qftpcompat.h>

Public Types

enum class  State {
  Unconnected , Connecting , Connected , LoggedIn ,
  Closing
}
 High-level connection state. More...
enum class  Error {
  NoError , HostNotFound , ConnectionRefused , NetworkTimeout ,
  NetworkError , NotConnected , NotLoggedIn , LoginFailed ,
  FileNotFound , PermissionDenied , ServerError , ParseError ,
  LocalFileError , Aborted , TransferFailed , UnknownError ,
  TlsHandshakeFailed , AuthTlsRejected
}
 Error codes set on the most recent failed command. More...
enum class  TransferMode { Passive , Active }
 FTP data channel mode. More...
enum class  TransferType { Binary , Ascii }
 FTP data representation type (RFC 959 §3.1.1). More...
enum class  EncryptionMode
 FTP encryption mode. \value None Plain FTP – default, fully backward-compatible. \value Explicit Explicit FTPS (AUTH TLS, port 21). \value Implicit Implicit FTPS (TLS from first byte, port 990).

Signals

void stateChanged (QFtpCompat::State newState)
 Emitted when the connection state changes.
void commandStarted (int id)
 Emitted when a queued command begins executing.
void commandFinished (int id, bool error)
 Emitted when a command completes (successfully or with error).
void done (bool error)
 Emitted when all queued commands have completed.
void listInfo (QFtpCompatDirEntry entry)
 Emitted once per entry during a list() command.
void dataTransferProgress (qint64 bytesTransferred, qint64 bytesTotal)
 Emitted periodically during data transfers.
void rawCommandReply (int code, QString detail)
 Emitted for rawCommand() responses and pwd() results.
void sslErrors (const QList< QSslError > &errors)
 Emitted when SSL/TLS errors occur.

Public Member Functions

int open (const QUrl &url, EncryptionMode mode=EncryptionMode::None)
 Connects to the FTP server and logs in using the URL credentials.
void close ()
 Sends QUIT and closes the connection gracefully.
void abort ()
 Aborts the current data transfer and clears the command queue.
int get (const QUrl &url, QIODevice *dst, TransferType type=TransferType::Binary)
 Downloads a remote file into dst.
int get (const QUrl &url, QByteArray *dst, TransferType type=TransferType::Binary)
 Downloads a remote file into dst byte array.
int put (const QUrl &url, const QByteArray &data, TransferType type=TransferType::Binary)
 Uploads data to the remote path in url.
int put (const QUrl &url, QIODevice *src, TransferType type=TransferType::Binary)
 Uploads data from src to the remote path in url.
int list (const QUrl &url)
 Requests a directory listing (LIST).
int mkdir (const QUrl &url)
 Creates a directory on the server (MKD).
int rmdir (const QUrl &url)
 Removes an empty directory on the server (RMD).
int remove (const QUrl &url)
 Deletes a file on the server (DELE).
int rename (const QUrl &from, const QUrl &to)
 Renames or moves a file on the server (RNFR + RNTO).
int cd (const QUrl &url)
 Changes the current working directory (CWD).
int pwd ()
 Requests the current working directory path (PWD).
int rawCommand (const QString &command)
 Sends an arbitrary FTP command on the control channel.
State state () const noexcept
 Current connection state.
Error error () const noexcept
 Error code set by the most recent failed command.
QString errorString () const noexcept
 Verbose, human-readable description of the last error.
int currentId () const noexcept
 ID of the command currently being executed, or -1 if idle.
bool hasPendingCommands () const noexcept
 true if commands are waiting in the queue.
void setSslConfiguration (const QSslConfiguration &config)
 Removes all pending (not yet started) commands from the queue.
QSslConfiguration sslConfiguration () const
 Returns the current SSL configuration.
void ignoreSslErrors ()
void resetConnection ()

Detailed Description

Asynchronous FTP client for Qt6.

Replaces the QFtp class that was removed from Qt5 and provides an identical asynchronous, command-queue-based API style.

Usage

auto *ftp = new QFtpCompat(this);
connect(ftp, &QFtpCompat::commandFinished, this, [ftp](int id, bool error) {
if (error)
qWarning() << "FTP error:" << ftp->errorString();
});
connect(ftp, &QFtpCompat::listInfo, this, [](QFtpCompatDirEntry e) {
qDebug() << e.toString();
});
ftp->open(QUrl("ftp://user:pass@192.168.1.1/"));
ftp->list(QUrl("ftp://192.168.1.1/flash/data/"));
ftp->get(QUrl("ftp://192.168.1.1/flash/data/config.cfg"), &buffer);
Represents a single entry from an FTP LIST response.
QString toString() const
Returns a human-readable summary for debug output.
void listInfo(QFtpCompatDirEntry entry)
Emitted once per entry during a list() command.
Error error() const noexcept
Error code set by the most recent failed command.
void commandFinished(int id, bool error)
Emitted when a command completes (successfully or with error).

Commands are queued and executed sequentially. Each method returns an integer ID that matches the id parameter in commandStarted and commandFinished.

Transfer modes

Only Passive mode (PASV) is implemented. Active mode (PORT) is reserved for future implementation.

Both Binary (TYPE I) and Ascii (TYPE A) transfer types are supported at the protocol level. CRLF normalisation for Ascii transfers is not yet applied in the data stream; see the Ascii note in TransferType.

Thread affinity

Must live on the thread that runs the Qt event loop (typically the main thread). Do not call any method from a different thread.

Date
2024 – Created
2026 – Updated

Definition at line 69 of file qftpcompat.h.

Member Enumeration Documentation

◆ Error

enum class QFtpCompat::Error
strong

Error codes set on the most recent failed command.

Enumerator
NoError 

No error since the last successful command.

HostNotFound 

DNS resolution failed.

ConnectionRefused 

Server actively refused the TCP connection.

NetworkTimeout 

No activity within the inactivity timeout.

NetworkError 

Generic socket error.

NotConnected 

Command issued without an active connection.

NotLoggedIn 

Command requires authentication.

LoginFailed 

USER/PASS rejected by the server.

FileNotFound 

Server returned 550 for a file operation.

PermissionDenied 

Server returned 553 / 550 permission error.

ServerError 

Unexpected server response code.

ParseError 

Failed to parse a server response (PASV, LIST).

LocalFileError 

Could not open or write to the local file/device.

Aborted 

Operation cancelled by abort().

TransferFailed 

Data channel closed before transfer completed.

UnknownError 

Catch-all for unclassified errors.

TlsHandshakeFailed 

TLS handshake failed on control or data channel.

AuthTlsRejected 

Server rejected the AUTH TLS command.

Definition at line 93 of file qftpcompat.h.

◆ State

enum class QFtpCompat::State
strong

High-level connection state.

Enumerator
Unconnected 

No TCP connection established.

Connecting 

TCP connect in progress.

Connected 

TCP connected, waiting for server greeting (220).

LoggedIn 

Authenticated; ready to accept commands.

Closing 

QUIT sent, waiting for server acknowledgement.

Definition at line 81 of file qftpcompat.h.

◆ TransferMode

enum class QFtpCompat::TransferMode
strong

FTP data channel mode.

Note
Only Passive is currently implemented. Active (PORT) is reserved for a future release.
Enumerator
Passive 

PASV – client opens the data connection (firewall-friendly).

Active 

PORT – server opens the data connection (not implemented).

Definition at line 121 of file qftpcompat.h.

◆ TransferType

enum class QFtpCompat::TransferType
strong

FTP data representation type (RFC 959 §3.1.1).

Note
Ascii sends TYPE A to the server and therefore starts a valid ASCII-mode transfer at the protocol level, but the library currently does not perform CRLF normalisation on the data stream. If your use case requires proper line-ending translation, apply it to the data before passing it to put(), or after receiving it from get().
Enumerator
Binary 

TYPE I – raw binary (8-bit) transfer. Fully implemented.

Ascii 

TYPE A – text transfer. Protocol-level TYPE sent; no CRLF transform (TODO).

Definition at line 137 of file qftpcompat.h.

Member Function Documentation

◆ abort()

void QFtpCompat::abort ( )

Aborts the current data transfer and clears the command queue.

Sends ABOR on the control channel. Emits commandFinished with error = true for the aborted command.

Definition at line 127 of file qftpcompat.cpp.

◆ cd()

int QFtpCompat::cd ( const QUrl & url)

Changes the current working directory (CWD).

Parameters
urlURL whose path is the target directory.
Returns
Command ID.

Definition at line 264 of file qftpcompat.cpp.

◆ close()

void QFtpCompat::close ( )

Sends QUIT and closes the connection gracefully.

Remaining queued commands are cleared. Emits done(false) when the server acknowledges the QUIT.

Definition at line 117 of file qftpcompat.cpp.

◆ commandFinished

void QFtpCompat::commandFinished ( int id,
bool error )
signal

Emitted when a command completes (successfully or with error).

Parameters
idCommand ID (matches the return value of the enqueue method).
errortrue if the command failed; inspect errorString() for details.

◆ commandStarted

void QFtpCompat::commandStarted ( int id)
signal

Emitted when a queued command begins executing.

Parameters
idCommand ID.

◆ dataTransferProgress

void QFtpCompat::dataTransferProgress ( qint64 bytesTransferred,
qint64 bytesTotal )
signal

Emitted periodically during data transfers.

Parameters
bytesTransferredBytes transferred so far.
bytesTotalTotal bytes to transfer, or -1 if unknown.

◆ done

void QFtpCompat::done ( bool error)
signal

Emitted when all queued commands have completed.

Parameters
errortrue if the last command in the queue failed.

◆ get() [1/2]

int QFtpCompat::get ( const QUrl & url,
QByteArray * dst,
TransferType type = TransferType::Binary )

Downloads a remote file into dst byte array.

Parameters
urlFull URL of the remote file.
dstByte array to append downloaded data to. Not owned.
typeTransfer type.
Returns
Command ID.

Definition at line 169 of file qftpcompat.cpp.

◆ get() [2/2]

int QFtpCompat::get ( const QUrl & url,
QIODevice * dst,
TransferType type = TransferType::Binary )

Downloads a remote file into dst.

Parameters
urlFull URL of the remote file.
dstOpen writable QIODevice. Not owned by QFtpCompat.
typeTransfer type (Binary recommended for binary files).
Returns
Command ID.

Definition at line 158 of file qftpcompat.cpp.

◆ ignoreSslErrors()

void QFtpCompat::ignoreSslErrors ( )

Instructs both sockets to ignore all pending SSL errors. Call from a sslErrors handler to accept self-signed certificates.

Definition at line 111 of file qftpcompat.cpp.

◆ list()

int QFtpCompat::list ( const QUrl & url)

Requests a directory listing (LIST).

Each parsed entry is emitted via listInfo before commandFinished is emitted.

Parameters
urlURL whose path is the directory to list. Use the root or an empty path to list the current directory.
Returns
Command ID.

Definition at line 218 of file qftpcompat.cpp.

◆ listInfo

void QFtpCompat::listInfo ( QFtpCompatDirEntry entry)
signal

Emitted once per entry during a list() command.

Parameters
entryParsed directory entry.

◆ mkdir()

int QFtpCompat::mkdir ( const QUrl & url)

Creates a directory on the server (MKD).

Parameters
urlURL whose path is the directory to create.
Returns
Command ID.

Definition at line 227 of file qftpcompat.cpp.

◆ open()

int QFtpCompat::open ( const QUrl & url,
EncryptionMode mode = EncryptionMode::None )

Connects to the FTP server and logs in using the URL credentials.

The url must contain at minimum a host. Port defaults to 21. User defaults to "anonymous", password to "anonymous\@".

Credentials can be embedded in the URL string or set via QUrl::setUserName() / QUrl::setPassword() – both forms are equivalent since the implementation reads url.userName() and url.password() regardless of how the QUrl was constructed:

// Inline in the URL string
ftp->open(QUrl("ftp://admin:secret@192.168.1.1/"));
// Via QUrl properties (e.g. when reading from QSettings)
QUrl url;
url.setScheme("ftp");
url.setHost(host);
url.setPort(port);
url.setUserName(user);
url.setPassword(password);
ftp->open(url);
Parameters
urlFTP URL carrying at minimum a host name.
Returns
Command ID for tracking via commandFinished.

Connect and log in.

Parameters
urlServer URL (scheme, host, port, user, password).
modeEncryption mode. Default: EncryptionMode::None (plain FTP – backward-compatible).

Definition at line 89 of file qftpcompat.cpp.

◆ put() [1/2]

int QFtpCompat::put ( const QUrl & url,
const QByteArray & data,
TransferType type = TransferType::Binary )

Uploads data to the remote path in url.

Parameters
urlFull URL of the remote destination.
dataData to upload. Copied internally.
typeTransfer type.
Returns
Command ID.

Definition at line 186 of file qftpcompat.cpp.

◆ put() [2/2]

int QFtpCompat::put ( const QUrl & url,
QIODevice * src,
TransferType type = TransferType::Binary )

Uploads data from src to the remote path in url.

Parameters
urlFull URL of the remote destination.
srcOpen readable QIODevice. Not owned by QFtpCompat.
typeTransfer type.
Returns
Command ID.
Note
All data is read from src into an internal buffer at command start. For streaming large files, consider pre-loading the data and using the QByteArray overload instead.

Definition at line 202 of file qftpcompat.cpp.

◆ pwd()

int QFtpCompat::pwd ( )

Requests the current working directory path (PWD).

The path is returned via rawCommandReply with code 257.

Returns
Command ID.

Definition at line 273 of file qftpcompat.cpp.

◆ rawCommand()

int QFtpCompat::rawCommand ( const QString & command)

Sends an arbitrary FTP command on the control channel.

The server response is emitted via rawCommandReply.

Parameters
commandRaw FTP command string (without CRLF).
Returns
Command ID.

Definition at line 281 of file qftpcompat.cpp.

◆ rawCommandReply

void QFtpCompat::rawCommandReply ( int code,
QString detail )
signal

Emitted for rawCommand() responses and pwd() results.

Parameters
codeFTP response code (e.g. 257 for PWD).
detailHuman-readable message text from the server.

◆ remove()

int QFtpCompat::remove ( const QUrl & url)

Deletes a file on the server (DELE).

Parameters
urlURL whose path is the file to delete.
Returns
Command ID.

Definition at line 245 of file qftpcompat.cpp.

◆ rename()

int QFtpCompat::rename ( const QUrl & from,
const QUrl & to )

Renames or moves a file on the server (RNFR + RNTO).

Parameters
fromURL whose path is the current file location.
toURL whose path is the new file location.
Returns
Command ID.

Definition at line 254 of file qftpcompat.cpp.

◆ resetConnection()

void QFtpCompat::resetConnection ( )

Hard-resets the FTP session: clears queue, aborts TCP sockets, sets state to Unconnected without sending QUIT. Safe to call in any state.

Definition at line 300 of file qftpcompat.cpp.

◆ rmdir()

int QFtpCompat::rmdir ( const QUrl & url)

Removes an empty directory on the server (RMD).

Parameters
urlURL whose path is the directory to remove.
Returns
Command ID.

Definition at line 236 of file qftpcompat.cpp.

◆ setSslConfiguration()

void QFtpCompat::setSslConfiguration ( const QSslConfiguration & config)

Removes all pending (not yet started) commands from the queue.

The currently executing command is not affected.

Sets the SSL configuration used for both control and data channels.

Call before open() to customise certificates, peer-verify mode, etc. The default configuration uses QSslSocket::VerifyPeer.

Embedded / self-signed servers
QSslConfiguration cfg = QSslConfiguration::defaultConfiguration();
cfg.setPeerVerifyMode(QSslSocket::VerifyNone);
ftp->setSslConfiguration(cfg);

Definition at line 99 of file qftpcompat.cpp.

◆ sslErrors

void QFtpCompat::sslErrors ( const QList< QSslError > & errors)
signal

Emitted when SSL/TLS errors occur.

To accept self-signed certificates (common on embedded servers):

void ignoreSslErrors()
void sslErrors(const QList< QSslError > &errors)
Emitted when SSL/TLS errors occur.

◆ stateChanged

void QFtpCompat::stateChanged ( QFtpCompat::State newState)
signal

Emitted when the connection state changes.

Parameters
newStateNew connection state.

The documentation for this class was generated from the following files: