Cross-Platform C++

ot::net
class FtpClient

#include "ot/net/FtpClient.h"

ot::net::TcpNetworkClient ot::ManagedObject Creates and manages a client connection with a remote FTP server. The FTP protocol, described in RFC 959, facilitates the transfer of files from one host to another. This class manages the socket connections with the remote server as well as providing a high-level interface to the commands that are defined by the protocol.

The following example shows how FtpClient can simply be used to retrieve a remote file using FTP:

    FtpClient ftp;
    try
    {
        // Connect to the remote FTP server and login as a guest
        ftp.connect(OT_T("ftp.gnu.org"));
        ftp.login(OT_T("anonymous"), OT_T("joe@example.com"));
        // Copy the file: welcome.msg to the local current directory
        String filename = OT_T("welcome.msg");
        RefPtr<FileOutputStream> rpOStream = new FileOutputStream(filename);
        ftp.retrieveFile(filename, rpOStream);
    }
    catch(IOException& e)
    {
        Console::cout() << e.toString() << endl;
    }

FTP Restart

FtpClient allows applications to restart failed transfers when the remote FTP server supports stream-mode restart. Stream-mode restart is not specified in RFC 959, but is specified in Extensions to FTP and is widely supported.

Where stream-mode restart is supported, restarting binary transfers is considerably easier than restarting ASCII transfers. This is due to the fact that the FTP SIZE command, which reports the size of the remote file, reports the transfer size of the file, which is not necessarily the same as the physical size of the file. The is described in more detail in the documentation for the getFileSize() method.




Constructor/Destructor Summary
FtpClient()
         Constructs a new FtpClient with default values for all properties.
~FtpClient()
         Disconnects from the remote FTP server before destroying this FtpClient.

Method Summary
 void abortDataTransfer()
         Forces the FTP server to abort the current data transfer operation (if any) and close the associated data connection.
 RefPtr< OutputStream > appendFile(const String& path)
         Returns an OutputStream that can be used to write to the specified file on the FTP server.
 void appendFile(const String& path, InputStream* pIn)
         Uses an InputStream as the source of bytes to write to the specified file on the FTP server.
 bool changeToParentDirectory()
         Changes the FTP server's working directory to the immediate parent of the current working directory by issuing a CDUP command.
 bool changeWorkingDirectory(const String& path)
         Changes the current working directory on the remote FTP server.
 void dataTransferComplete()
         Tests whether the preceding data transfer request completed successfully.
 bool getCheckInboundConnection() const
         Returns the value of the CheckInboundConnection property.
 size_t getDataConnectionTimeout() const
         Returns the timeout value (in milliseconds) used when establishing passive or active data connections.
 DataConnectionType getDataConnectionType() const
         Returns the type of data connection to be used: FtpClient::Active or FtpClient::Passive.
protected  virtual int getDefaultPort() const
         Returns the default port for FTP, which is 21.
 size_t getFileSize(const String& path)
         Returns the transfer size of the remote file.
 TransferType getTransferType() const
         Returns the transfer type that will be used for subsequent data operations: FtpClient::Ascii or FtpClient::Binary.
 RefPtr< InputStream > listDetails(const String& spec)
         Retrieves from the FTP server a directory listing of the current directory and makes it available as an InputStream.
 RefPtr< InputStream > listNames(const String& spec)
         Retrieves from the FTP server a list of file names from the current directory and makes it available as an InputStream.
 void login(const String& user, const String& password)
         Sends a login request to the remote FTP server.
protected  virtual void postConnect(const String& server, int port, size_t timeoutMS)
         Protected function called when a socket connection has been established with the TCP/IP network server.
 virtual void preDisconnect()
         Protected function called when a socket connection is about to be closed from the client side.
 String printWorkingDirectory()
         Returns the FTP server's current working directory.
 void renameFile(const String& from, const String& to)
         Renames a file on the remote FTP server.
 RefPtr< InputStream > retrieveFile(const String& path, size_t offset)
         Retrieves the specified file from the remote server and makes it available as an InputStream.
 void retrieveFile(const String& path, OutputStream* pOut, size_t offset)
         Retrieves the specified file from the remote server and copies it to the supplied OutputStream.
 void setCheckInboundConnection(bool bCheckInboundConnection)
         Sets the CheckInboundConnection property.
 void setDataConnectionTimeout(size_t timeoutMS)
         Sets a timeout value for establishing a data connection.
 void setDataConnectionType(DataConnectionType type)
         Sets the type of data connection to be used for subsequent data transmission operations.
 void setTransferType(TransferType type)
         Sets the transfer type that will be used for subsequent data operations: TransferType::Ascii or TransferType::Binary.
 RefPtr< OutputStream > storeFile(const String& path, size_t offset)
         Returns an OutputStream that can be used to write to the specified file on the FTP server.
 void storeFile(const String& path, InputStream* pIn, size_t offset)
         Uses an InputStream as the source of bytes to write to the specified file on the FTP server.

Methods inherited from class ot::ManagedObject
addRef, getRefCount, onFinalRelease, operator=, release

Methods inherited from class ot::net::TcpNetworkClient
connect, createConnection, disconnect, getInputStream, getLocalAddress, getOutputStream, getServerAddress, getServerPort, isConnected

Enumerations

enum DataConnectionType { Passive /* Client connects to the (passive) server for data transfers */ 
  Active /* (Active) server connects to the client for data transfers */ 



enum TransferType { Binary /* Treats files an an opaque stream of bytes */ 
  Ascii /* Translates line-feeds into the appropriate local format */ 


Constructor/Destructor Detail

FtpClient

 FtpClient()
Constructs a new FtpClient with default values for all properties.


~FtpClient

 ~FtpClient()
Disconnects from the remote FTP server before destroying this FtpClient.

Note:
It is possible to destroy an FtpClient while a data transfer operation is still in progress. Even though the control connection with the remote server will be closed, the data connection will remain open until the transfer is complete.

Method Detail

abortDataTransfer

void abortDataTransfer()
Forces the FTP server to abort the current data transfer operation (if any) and close the associated data connection.

Exceptions:
IOException - if an error occurs sending the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.

appendFile

RefPtr< OutputStreamappendFile(const String& path)
Returns an OutputStream that can be used to write to the specified file on the FTP server. If the file already exists, the data written to the OutputStream is appended to the existing file; otherwise a new file is created.

Parameters:
path - the file name to append to
Returns:
An OutputStream attached to the remote file.
Exceptions:
IOException - if an error occurs appending to the file on the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.

appendFile

void appendFile(const String& path,
                InputStream* pIn)
Uses an InputStream as the source of bytes to write to the specified file on the FTP server. If the file already exists, the InputStream data is appended to the end of the file, otherwise a new file is created.

Parameters:
path - the file name to append to
pIn - the InputStream source
Exceptions:
IOException - if an error occurs either reading from the InputStream or transmitting the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
NullPointerException - if pIn is null.
IllegalStateException - if the FtpClient is not connected.

changeToParentDirectory

bool changeToParentDirectory()
Changes the FTP server's working directory to the immediate parent of the current working directory by issuing a CDUP command.

Returns:
true if the current working directory was changed; false otherwise.
Exceptions:
IOException - if an error occurs sending the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.

changeWorkingDirectory

bool changeWorkingDirectory(const String& path)
Changes the current working directory on the remote FTP server.

Parameters:
path - the name of the directory
Returns:
true if the current working directory was changed; false otherwise
Exceptions:
IOException - if an error occurs sending the request to the FTP server
ProtocolException - if an invalid response is received from the FTP server
IllegalStateException - if the FtpClient is not connected.

dataTransferComplete

void dataTransferComplete()
Tests whether the preceding data transfer request completed successfully. Asynchronous data transfer requests (i.e. read operations that return an InputStream or write operations that return an OutputStream) signal their completion by returning InputStream::EndOfFile (for read) or by the application closing the OutputStream (for write). In both cases, the remote FTP server sends a response message on the control connection to indicate if the remote operation completed successfully. This method interrogates the response and indicates the success of the operation.

Exceptions:
IOException - if an error occurs reading the response from the FTP server
ProtocolException - if an invalid response is received from the FTP server

getCheckInboundConnection

bool getCheckInboundConnection() const
Returns the value of the CheckInboundConnection property. When this is true, inbound connection attempts from remote FTP servers are checked to ensure they originate from the same host as the FTP server to which this FtpClient is connected.

See also:
setCheckInboundConnection()

getDataConnectionTimeout

size_t getDataConnectionTimeout() const
Returns the timeout value (in milliseconds) used when establishing passive or active data connections.

See also:
setDataConnectionTimeout()

getDataConnectionType

DataConnectionType getDataConnectionType() const
Returns the type of data connection to be used: FtpClient::Active or FtpClient::Passive.

See also:
setDataConnectionType()

getDefaultPort

protected virtual int getDefaultPort() const
Returns the default port for FTP, which is 21.


getFileSize

size_t getFileSize(const String& path)
Returns the transfer size of the remote file. This uses the SIZE FTP command which is not defined in RFC 959, but is usually implemented by FTP servers nonetheless.

The SIZE command is supposed to return the transfer size of the file, which is determined for the transfer mode in operation. For IMAGE mode, this will equate to the size (in bytes) of the remote file. For ASCII mode, this will equate to the number of bytes that will be used to transfer the file over the network, with line-feeds translated into <CRLF> pairs.

Using getFileSize() to control restart operations

getFileSize() can be used to restart remote store operations if the transfer mode is IMAGE (binary), but care must be taken when using it for ASCII mode transfers from UNIX-based hosts.

Line feeds in text files on UNIX hosts are represented by a single <LF> character, and therefore, if a local file is fully transfered to a remote host, the getFileSize() command is likely to report a size larger than the actual size of the local file.

Parameters:
path - the path name of the file
Exceptions:
IOException - if an error occurs retrieving the file size from the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.

getTransferType

TransferType getTransferType() const
Returns the transfer type that will be used for subsequent data operations: FtpClient::Ascii or FtpClient::Binary.

See also:
setTransferType()

listDetails

RefPtr< InputStreamlistDetails(const String& spec)
Retrieves from the FTP server a directory listing of the current directory and makes it available as an InputStream. The application should read from the InputStream until it receives an EndOfFile marker. At this point the application should check the success of the remote operations by calling dataTransferComplete().

If this FtpClient is going to be used for further operations it is essential that dataTransferComplete() is called. However, if the application is not interested in testing the success of the transfer, and no other FTP operations are required, the FtpClient may be deleted before the InputStream is fully processed.

Parameters:
spec - a filename specification which may be used by the server to control which files are listed.
Returns:
An InputStream containing the results of the FTP LIST command.
Exceptions:
IOException - if an error occurs sending the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.
See also:
dataTransferComplete()

listNames

RefPtr< InputStreamlistNames(const String& spec)
Retrieves from the FTP server a list of file names from the current directory and makes it available as an InputStream. The application should read from the InputStream until it receives an EndOfFile marker. At this point the application should check the success of the remote operations by calling dataTransferComplete().

If this FtpClient is going to be used for further operations it is essential that dataTransferComplete() is called. However, if the application is not interested in testing the success of the transfer, and no other FTP operations are required, the FtpClient may be deleted before the InputStream is fully processed.

Parameters:
spec - a filename specification which may be used by the server to control which files are listed.
Returns:
An InputStream containing the results of the FTP NLST command.
Exceptions:
IOException - if an error occurs sending the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.
See also:
dataTransferComplete()

login

void login(const String& user,
           const String& password)
Sends a login request to the remote FTP server. Note that the user name and password are sent over the network in plain text, so it is not a good idea to use FTP authentication with sensitive data or passwords.

Parameters:
user - the userid
password - the password
Exceptions:
IOException - if an error occurs sending the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.

postConnect

protected virtual void postConnect(const String& server,
                                   int port,
                                   size_t timeoutMS)
Protected function called when a socket connection has been established with the TCP/IP network server. If this method is overridden in classes derived from FtpClient, it is important that this base class implementation is called in order to perform necessary initialization.


preDisconnect

virtual void preDisconnect()
Protected function called when a socket connection is about to be closed from the client side. The base class implementation does nothing.


printWorkingDirectory

String printWorkingDirectory()
Returns the FTP server's current working directory.

Exceptions:
IOException - if an error occurs sending the request to the FTP server
ProtocolException - if an invalid response is received from the FTP server

renameFile

void renameFile(const String& from,
                const String& to)
Renames a file on the remote FTP server.

Parameters:
from - the name of the existing file.
to - the new name for the file.
Exceptions:
IOException - if an error occurs renaming the file.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.

retrieveFile

RefPtr< InputStreamretrieveFile(const String& path,
                                   size_t offset)
Retrieves the specified file from the remote server and makes it available as an InputStream. The application should read from the InputStream until it receives an EndOfFile marker. At this point the application should check the success of the remote operation by calling dataTransferComplete().

If this FtpClient is going to be used for further operations it is essential that dataTransferComplete() is called. However, if the application is not interested in testing the success of the transfer, and no other FTP operations are required, the FtpClient may be deleted before the InputStream is fully processed.

This method can be used to restart a failed retrieve operation by specifying a value for the offset parameter. Note that this value refers to the number of bytes to skip from the network transfer, not a number of bytes from the remote file. However, for binary transfers, these two values are the same.

Parameters:
path - the file name to retrieve.
offset - the number of bytes of the transfer to skip.
Returns:
An InputStream attached to the remote file.
Exceptions:
IOException - if an error occurs retrieving the file from the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
ProtocolException - if a value has been provided for the offset parameter and the FTP server does not support the REST command for stream-mode operations.
IllegalStateException - if the FtpClient is not connected.
See also:
dataTransferComplete()

retrieveFile

void retrieveFile(const String& path,
                  OutputStream* pOut,
                  size_t offset)
Retrieves the specified file from the remote server and copies it to the supplied OutputStream. This method can be used to restart a failed retrieve operation by specifying a value for the offset parameter. Note that this value refers to the number of bytes to skip from the network transfer, not a number of bytes from the remote file. However, for binary transfers, these two values are the same.

Parameters:
path - the file name to retrieve.
pOut - the OutputStream which will act as a sink for the file.
offset - the number of bytes of the transfer to skip.
Exceptions:
NullPointerException - if pOut is null.
IOException - if an error occurs retrieving the file from the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
ProtocolException - if a value has been provided for the offset parameter and the FTP server does not support the REST command for stream-mode operations.
IllegalStateException - if the FtpClient is not connected.

setCheckInboundConnection

void setCheckInboundConnection(bool bCheckInboundConnection)
Sets the CheckInboundConnection property. When true (the default), connection attempts from remote hosts will be checked to ensure they come from the same network host as the FTP control connection. An IOException is thrown if a connection request comes from a different host.

This only takes effect when Active data connections are being used.

See also:
getCheckInboundConnection()

setDataConnectionTimeout

void setDataConnectionTimeout(size_t timeoutMS)
Sets a timeout value for establishing a data connection.

Parameters:
timeoutMS - the number of milliseconds that the FtpClient will wait for a data connection to be established before timing out. A value of zero forces the FtpClient to wait forever.
See also:
getDataConnectionTimeout()

setDataConnectionType

void setDataConnectionType(DataConnectionType type)
Sets the type of data connection to be used for subsequent data transmission operations. Two types of data connection are supported:- The default connection type is Active as this was the original mode of operation in early FTP implementations. However, the Active mode can present difficulties when attempting to communicate through firewall software; Passive mode is often preferable in this situation.

Parameters:
type - the data connection type to be used.
See also:
getDataConnectionType()

setTransferType

void setTransferType(TransferType type)
Sets the transfer type that will be used for subsequent data operations: TransferType::Ascii or TransferType::Binary. Binary transfers treat files as an opaque stream of bytes whereas Ascii transfers translate line-feeds into <CRLF> pairs for transmission over the network, and then translate these back into the format appropriate for the target platform.

Exceptions:
IOException - if an error occurs sending the request to the FTP server
ProtocolException - if an invalid response is received from the FTP server
See also:
getTransferType()

storeFile

RefPtr< OutputStreamstoreFile(const String& path,
                                 size_t offset)
Returns an OutputStream that can be used to write to the specified file on the FTP server. The application should write data to the OutputStream, finally closing the OutputStream to signal the end of file. At this point the application should check the success of the remote operation by calling dataTransferComplete().

If this FtpClient is going to be used for further operations it is essential that dataTransferComplete() is called. However, if the application is not interested in testing the success of the transfer, and no other FTP operations are required, the FtpClient may be deleted before the OutputStream is closed.

This method can be used to restart a failed store operation by specifying a value for the offset parameter. Note that this value refers to the number of equivalent network transfer bytes to seek to in the remote file, which may not be the same as the physical offset within the remote file for ASCII-mode transfers. For binary transfers, these two values may be considered the same.

Parameters:
path - the file name to store.
offset - the number of network transfer bytes that the remote FTP server will seek past before recommencing the store operation.
Returns:
An OutputStream attached to the remote file.
Exceptions:
IOException - if an error occurs sending the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
ProtocolException - if a value has been provided for the offset parameter and the FTP server does not support the REST command for stream-mode operations.
IllegalStateException - if the FtpClient is not connected.

storeFile

void storeFile(const String& path,
               InputStream* pIn,
               size_t offset)
Uses an InputStream as the source of bytes to write to the specified file on the FTP server. This method can be used to restart a failed store operation by specifying a value for the offset parameter. Note that this value refers to the number of equivalent network transfer bytes to seek to in the remote file, which may not be the same as the physical offset within the remote file for ASCII-mode transfers. For binary transfers, these two values may be considered the same.

Parameters:
path - the file name to store
pIn - the InputStream source
offset - the number of network transfer bytes that the remote FTP server will seek past before recommencing the store operation.
Exceptions:
NullPointerException - if pIn is null.
IOException - if an error occurs sending the request to the FTP server.
ProtocolException - if an invalid response is received from the FTP server.
IllegalStateException - if the FtpClient is not connected.


Cross-Platform C++

Found a bug or missing feature? Please email us at support@elcel.com

Copyright © 2000-2003 ElCel Technology   Trademark Acknowledgements