SmartFTP FTP Library
ISFTPConnection Interface Reference

import "sfFTPLib.idl";

Public Member Functions

HRESULT Close ()
 Closes the connection.
HRESULT Abort ()
 Cancels the currently executing blocking operation.
HRESULT Connect ()
 Initializes the SFTP subsystem over the existing SSH session.
HRESULT Disconnect ()
 Terminates the SFTP subsystem session.
HRESULT NewFile ([in] BSTR remoteFile)
 Creates a new, empty file on the remote server.
HRESULT DownloadFile ([in] BSTR remoteFile, [in] VARIANT localFile, [in] DataTransferType transferType, [in] long startPositionLo, [in] long startPositionHi)
 Transfers a file from the remote server to the local system.
HRESULT DownloadFileEx ([in] BSTR remoteFile, [in] VARIANT localFile, [in] DataTransferType transferType, [in] ULONGLONG startPosition, [in] ULONGLONG endPosition, [in] long flags, [in] ITransferProgressEvents *progress)
 An advanced method to transfer a file (or file range) from the remote server with progress callbacks and optional flags.
HRESULT UploadFile ([in] VARIANT localFile, [in] BSTR remoteFile, [in] DataTransferType transferType, [in] long startPositionLo, [in] long startPositionHi)
 Transfers a file or stream from the local system to the remote server.
HRESULT UploadFileEx ([in] VARIANT localFile, [in] BSTR remoteFile, [in] DataTransferType transferType, [in] ULONGLONG startPosition, [in] ITransferProgressEvents *progress)
 An advanced method to upload data to the remote server with progress tracking.
HRESULT Rename ([in] BSTR oldPath, [in] BSTR newPath, [in] long flags)
 Renames or moves a file/directory on the remote server.
HRESULT RemoveFile ([in] BSTR file)
 Deletes a specific file from the remote server.
HRESULT RemoveDirectory ([in] BSTR directory)
 Deletes an empty directory from the remote server.
HRESULT MakeDirectory ([in] BSTR directory)
 Creates a new directory on the remote server.
HRESULT ReadDirectory ([in] BSTR directory, [out, retval] IFTPItems **retval)
 Retrieves a collection of files and subdirectories from a remote directory.
HRESULT ReadDirectoryEx ([in] BSTR directory, [in] ITransferProgressEvents *progress, [out, retval] IFTPItems **retval)
 An advanced version of ReadDirectory that supports progress monitoring.
HRESULT RealPath ([in] BSTR original, [out, retval] BSTR *retval)
 Resolves a relative or symbolic path into its canonical absolute equivalent on the server.
HRESULT RealPathEx ([in] BSTR original, [in] long flags, [in] BSTR component, [out, retval] BSTR *retval)
 An extended path resolution method supporting SFTP v6 control flags.
HRESULT Stat ([in] BSTR path, [in] long flags, [out, retval] IFTPItem **retval)
 Retrieves information and attributes for a file or directory.
HRESULT LStat ([in] BSTR path, [in] long flags, [out, retval] IFTPItem **retval)
 Retrieves information for a file, directory, or symbolic link (without following the link).
HRESULT StatEx ([in] BSTR path, [in] long flags, VARIANT_BOOL followLink, [out, retval] IFTPItem **retval)
 An extended attribute retrieval method with explicit symbolic link control.
HRESULT SetStat ([in] BSTR path, [in] IFTPItem *item)
 Updates the attributes of a remote file or directory.
HRESULT ReadLink ([in] BSTR path, [out, retval] BSTR *retval)
 Reads the target path of a symbolic link.
HRESULT Link ([in] BSTR path, [in] BSTR linkPoint, [in] VARIANT_BOOL symbolicLink)
 Creates a link (symbolic or hard) on the remote server.
HRESULT StatVFS ([in] BSTR path, [out, retval] ISFTPStatVFS **retval)
 Retrieves information about the remote file system's capacity and limits.
HRESULT GetFileHash ([in] HashAlgo algo, [in] BSTR path, [in] ULONGLONG offset, [in] ULONGLONG length, [out, retval] ISFTPExtendedCheckFileResult **retval)
 Calculates a cryptographic hash of a remote file or a specific byte range.
HRESULT GetSpaceAvailable ([in] BSTR path, [out, retval] ISFTPSpaceAvailable **retval)
 Retrieves the available and total disk space for a specific path in bytes.
HRESULT CopyFile ([in] BSTR sourceFile, [in] BSTR destinationFile, [in] VARIANT_BOOL overwrite)
 Copies a file from one location to another directly on the remote server.
HRESULT SetFileLogger ([out, retval] IFileLogger **fileLogger)
 Creates a file logger sfFTPLib::FileLogger and attaches it to the Logger property.

Properties

VARIANT_BOOL Busy [get]
 Indicates whether the connection is currently executing an operation.
VARIANT_BOOL UseMessageLoop [get, set]
 Controls whether the component processes Windows messages during blocking operations.
long Timeout [get, set]
 Sets the maximum time (in seconds) to wait for a network operation to complete.
ISSHConnection SSHConnection [get]
 Accesses the underlying Secure Shell (SSH) transport interface.
long ProtocolVersionPreference [get, set]
 Controls the preferred version of the SFTP protocol to negotiate with the server.
BSTR SFTPServerCommand [get, set]
 Specifies the command or subsystem name used to initialize the SFTP session on the remote server.
BSTR ServerLineTerminator [get, set]
 Specifies the line ending sequence used by the remote server for text-based operations.
long ProtocolVersion [get]
 Retrieves the SFTP protocol version currently in use for the active session.
SFTPConnectionStatus Status [get]
 Retrieves the current operational state of the SFTP subsystem.
ISFTPVendorId VendorId [get, set]
 Configures the software identification data that the client sends to the server.
ILogger Logger [set]
 Attaches a logging mechanism to the SFTP session for debugging and auditing.
SFTPStatus LastStatusCode [get]
 Retrieves the most recent protocol-level status code returned by the SFTP server.
BSTR LastStatusMessage [get]
 Retrieves the human-readable error message returned by the SFTP server for the last operation.
ULONGLONG LastTransferBytes [get]
 Retrieves the total number of bytes transferred during the last SFTP transfer.
long LastTransferBytesLo [get]
 Retrieves the lower 32 bits of the last transfer size.
long LastTransferBytesHi [get]
 Retrieves the upper 32 bits of the last transfer size.
long LastTransferTime [get]
 Retrieves the duration of the last SFTP transfer in milliseconds.
long LastTransferSpeed [get]
 Retrieves the average data transfer rate of the last SFTP transfer.
long CodePage [get, set]
 Specifies the character encoding used to interpret filenames on the remote server.
ISFTPServerState ServerState [get]
 Accesses the read-only object describing the capabilities and identity of the connected SFTP server.

Member Function Documentation

◆ Abort()

HRESULT ISFTPConnection::Abort ( )

Cancels the currently executing blocking operation.

◆ Close()

HRESULT ISFTPConnection::Close ( )

Closes the connection.

To ungracefully close the connection use the Disconnect method.

◆ Connect()

HRESULT ISFTPConnection::Connect ( )

Initializes the SFTP subsystem over the existing SSH session.

The Sequence: Calling this method triggers the specific SFTP protocol negotiation:

  1. Channel Allocation: Requests a new logical channel ID from the SSH server.
  2. Subsystem Request: Sends an SSH_MSG_CHANNEL_REQUEST to start the "sftp" subsystem.
  3. Protocol Handshake: Sends SSH_FXP_INIT (with the client's version) and waits for SSH_FXP_VERSION.
  4. State Population: Parses the server's response to populate the ServerState object (extensions, limits, etc.).

◆ CopyFile()

HRESULT ISFTPConnection::CopyFile ( [in] BSTR sourceFile,
[in] BSTR destinationFile,
[in] VARIANT_BOOL overwrite )

Copies a file from one location to another directly on the remote server.

The Operation: This method utilizes the copy-file extension (often implemented by modern servers like OpenSSH or Bitvise) or the native SFTP v6 SSH_FXP_EXTENDED "copy-data" command.

Overwrite Behavior:

  • If overwrite is VARIANT_TRUE: The destinationFile will be replaced if it exists.
  • If overwrite is VARIANT_FALSE: The method will fail with an error (typically SSH_FX_FILE_ALREADY_EXISTS) if the destination already exists.
Parameters
[in]sourceFileThe full absolute path of the existing file to be copied.
[in]destinationFileThe full absolute path where the copy should be created.
[in]overwriteDetermines whether to replace an existing file at the destination.

◆ Disconnect()

HRESULT ISFTPConnection::Disconnect ( )

Terminates the SFTP subsystem session.

The Scope: This method strictly shuts down the SFTP application layer. It closes the specific SSH channel used for file transfers and releases any internal resources (like open file handles or directory listing caches).

The Protocol:

  1. Sends an SSH_MSG_CHANNEL_CLOSE message for the SFTP channel ID.
  2. Waits for the server to acknowledge the channel closure.
  3. Invalidates the ServerState object.

◆ DownloadFile()

HRESULT ISFTPConnection::DownloadFile ( [in] BSTR remoteFile,
[in] VARIANT localFile,
[in] DataTransferType transferType,
[in] long startPositionLo,
[in] long startPositionHi )

Transfers a file from the remote server to the local system.

The Operation: This method initiates a download sequence:

  1. Opens the remoteFile on the server using SSH_FXP_OPEN.
  2. Seeks to the specified start position (for resuming).
  3. Reads data in chunks via SSH_FXP_READ.
  4. Writes the data to the localFile destination.
  5. Closes the remote handle.

Flexible Destination (localFile): The localFile parameter is a VARIANT that accepts two types of input:

  • String (BSTR): The full absolute path to a file on the local disk. If the file exists, it will be overwritten (unless resuming).
  • Object (IStream*): A COM interface pointer to a writable stream. This allows you to download data directly into memory, a database blob, or another custom target without creating a temporary file on disk.

Resuming Transfers: To resume a broken download, pass the size of the existing partial local file as the start position. The 64-bit offset is split into two 32-bit integers: Offset = (startPositionHi * 2^32) + startPositionLo

Parameters
[in]remoteFileThe full absolute path of the file on the server to download.
[in]localFileThe destination: either a local file path (String) or a writable COM stream (IStream).
[in]transferTypeThe mode of transfer defined by the DataTransferType enum.
[in]startPositionLoThe lower 32 bits of the starting byte offset (Resume position).
[in]startPositionHiThe upper 32 bits of the starting byte offset.

◆ DownloadFileEx()

HRESULT ISFTPConnection::DownloadFileEx ( [in] BSTR remoteFile,
[in] VARIANT localFile,
[in] DataTransferType transferType,
[in] ULONGLONG startPosition,
[in] ULONGLONG endPosition,
[in] long flags,
[in] ITransferProgressEvents * progress )

An advanced method to transfer a file (or file range) from the remote server with progress callbacks and optional flags.

The "Extended" Capabilities: Unlike the standard DownloadFile, this method offers:

  1. Range Support: You can download specific chunks of a file (e.g., bytes 100 to 200) by setting startPosition and endPosition.
  2. Native 64-bit: Uses ULONGLONG directly, eliminating the need to split offsets into High/Low parts.
  3. Behavior Control: The flags parameter allows you to handle edge cases like reading past the end of the file.
  4. Event Callbacks: Accepts an ITransferProgressEvents interface to report granular progress.

Usage Scenarios:

  • Resuming: Set startPosition to the size of the local partial file and endPosition to 0 (read to end).
  • Parallel Downloading: Download a large file in multiple streams by requesting different ranges (e.g., Thread 1: 0-10MB, Thread 2: 10-20MB).
  • Fixed Buffer Reads: Request a specific size (e.g., 1MB) and use the sfFTPLib::ftpDownloadFlagReadBeyondEnd flag to prevent errors if the file is smaller than expected.
Parameters
[in]remoteFileThe full absolute path of the source file on the server.
[in]localFileThe destination: either a local file path (String) or a writable COM stream (IUnknown/IStream).
[in]transferTypeThe mode of transfer defined by the DataTransferType enum (Binary, ASCII, etc.).
[in]startPositionThe byte offset at which to begin reading (inclusive). 0 starts at the beginning.
[in]endPositionThe byte offset at which to stop reading (exclusive).
[in]flagsA bitmask of values from the sfFTPLib::DownloadFlags enumeration:
[in]progressA pointer to an implementation of ITransferProgressEvents. The component will call ITransferProgressEvents::OnTransferProgress during the transfer. Pass NULL if monitoring is not required.

◆ GetFileHash()

HRESULT ISFTPConnection::GetFileHash ( [in] HashAlgo algo,
[in] BSTR path,
[in] ULONGLONG offset,
[in] ULONGLONG length,
[out, retval] ISFTPExtendedCheckFileResult ** retval )

Calculates a cryptographic hash of a remote file or a specific byte range.

The Operation: This method sends a check-file extended request to the server. The server reads the data from its local disk, computes the hash, and returns only the resulting digest.

Partial Hashing: You can hash specific segments of a file by utilizing the offset and length parameters. This is ideal for verifying individual chunks in a multi-part upload or identifying which part of a file has changed.

The Return Value: Returns an ISFTPExtendedCheckFileResult object which contains the raw hash bytes and the algorithm actually used by the server.

Parameters
[in]algoThe desired hashing algorithm (e.g., MD5, SHA-1, SHA-256) defined by the HashAlgo enum.
[in]pathThe full absolute path to the file on the server.
[in]offsetThe byte offset at which to start the hash calculation. Set to 0 for the start of the file.
[in]lengthThe number of bytes to include in the hash. Set to 0 to hash everything from the offset to the end of the file.
[out]retvalReceives an ISFTPExtendedCheckFileResult interface containing the computed digest.

◆ GetSpaceAvailable()

HRESULT ISFTPConnection::GetSpaceAvailable ( [in] BSTR path,
[out, retval] ISFTPSpaceAvailable ** retval )

Retrieves the available and total disk space for a specific path in bytes.

The Operation: This method utilizes the space-available extension as defined in the IETF SSH File Transfer Protocol Extensions Draft.

Parameters
[in]pathAny valid absolute path on the target file system (e.g., the upload destination).
[out]retvalReceives a pointer to an ISFTPSpaceAvailable object.

◆ Link()

HRESULT ISFTPConnection::Link ( [in] BSTR path,
[in] BSTR linkPoint,
[in] VARIANT_BOOL symbolicLink )

Creates a link (symbolic or hard) on the remote server.

The Operation: This method creates a pointer at linkPoint that refers to the existing object at path.

Link Types:

  • Symbolic Link (symbolicLink = VARIANT_TRUE): Creates a "soft" link. This is a special file that contains the text path of the target. It can cross filesystem boundaries and point to directories.
  • Hard Link (symbolicLink = VARIANT_FALSE): Creates an additional directory entry for an existing file. It shares the same inode as the original and cannot point to directories or cross filesystems.

Protocol Support & Limitations:

  • SFTP v3: This version of the protocol only natively supports symbolic links via the SSH_FXP_SYMLINK packet. Consequently, the symbolicLink parameter is ignored and a symbolic link is always created. Hard linking is not available in standard v3.
  • SFTP v6: Uses the unified SSH_FXP_LINK packet, which fully honors the symbolicLink flag to choose between symbolic and hard links.
Parameters
[in]pathThe existing file or directory that the link will point to (the "target").
[in]linkPointThe absolute path where the new link should be created.
[in]symbolicLinkSet to VARIANT_TRUE for a symbolic link, or VARIANT_FALSE for a hard link. (Note: Ignored and treated as VARIANT_TRUE in SFTP v3).

◆ LStat()

HRESULT ISFTPConnection::LStat ( [in] BSTR path,
[in] long flags,
[out, retval] IFTPItem ** retval )

Retrieves information for a file, directory, or symbolic link (without following the link).

The Operation: Sends an SSH_FXP_LSTAT request. Unlike Stat, if the path is a symbolic link, this method returns information about the link itself rather than the target it points to.

Use Case: Essential for synchronization or backup tools that need to identify and recreate links rather than downloading the linked content.

Parameters
[in]pathThe full absolute path to the remote object.
[in]flagsA bitmask of sfFTPLib::SFTPItemAttribute (SFTP v4+) indicating which attributes are requested.
[out]retvalReceives an IFTPItem describing the object (or the link itself).

◆ MakeDirectory()

HRESULT ISFTPConnection::MakeDirectory ( [in] BSTR directory)

Creates a new directory on the remote server.

The Operation: This method sends an SSH_FXP_MKDIR request to the server.

Behavior and Constraints:

  • Parent Existence: Most SFTP servers require the parent directory to already exist. For example, to create /data/logs/2026, the directory /data/logs must already be present.
  • Collision: If a directory or file with the same name already exists at the specified path, this method will return an error (typically SSH_FX_FILE_ALREADY_EXISTS).
Parameters
[in]directoryThe full absolute path of the new directory to be created.

◆ NewFile()

HRESULT ISFTPConnection::NewFile ( [in] BSTR remoteFile)

Creates a new, empty file on the remote server.

The Operation: This method sends an SSH_FXP_OPEN request with the SSH_FXF_CREAT and SSH_FXF_TRUNC flags (along with SSH_FXF_WRITE).

Behavior:

  • If the file does not exist: A new, zero-byte file is created.
  • If the file already exists: The file is truncated (its content is wiped), resulting in a zero-byte file.
Parameters
[in]remoteFileThe full absolute path to the file to be created.

◆ ReadDirectory()

HRESULT ISFTPConnection::ReadDirectory ( [in] BSTR directory,
[out, retval] IFTPItems ** retval )

Retrieves a collection of files and subdirectories from a remote directory.

The Operation: This is a high-level method that encapsulates the following SFTP packet flow:

  1. SSH_FXP_OPENDIR: Requests a handle for the directory path.
  2. SSH_FXP_READDIR: Repeatedly fetches batches of names and attributes until EOF is reached.
  3. SSH_FXP_CLOSE: Releases the directory handle on the server.

The Result: Returns an IFTPItems collection containing IFTPItem objects. Each item includes essential metadata such as size, permissions, and modification timestamps.

Parameters
[in]directoryThe full absolute path of the directory to list.
[out]retvalReceives the IFTPItems collection interface.

◆ ReadDirectoryEx()

HRESULT ISFTPConnection::ReadDirectoryEx ( [in] BSTR directory,
[in] ITransferProgressEvents * progress,
[out, retval] IFTPItems ** retval )

An advanced version of ReadDirectory that supports progress monitoring.

Why use Extended? For directories containing a massive number of entries (thousands of files), the listing process can take several seconds. This method allows the calling thread to stay informed during the retrieval process.

Progress Reporting: The ITransferProgressEvents::OnTransferProgress callback is triggered each time a new batch of directory entries is successfully received from the server.

Parameters
[in]directoryThe full absolute path of the directory to list.
[in]progressA pointer to an ITransferProgressEvents implementation. Pass NULL to disable reporting.
[out]retvalReceives the IFTPItems collection interface.

◆ ReadLink()

HRESULT ISFTPConnection::ReadLink ( [in] BSTR path,
[out, retval] BSTR * retval )

Reads the target path of a symbolic link.

The Operation: This method sends an SSH_FXP_READLINK request to the server. It is used to discover where a symbolic link points without actually opening the target file.

Behavior:

  • If the path provided is a valid symbolic link, the method returns the path string stored within the link.
  • If the path is a regular file or directory (not a link), the server will typically return an error (e.g., SSH_FX_BAD_MESSAGE or SSH_FX_FAILURE).
Parameters
[in]pathThe full absolute path of the symbolic link to inspect.
[out]retvalReceives the path string representing the target of the link.

◆ RealPath()

HRESULT ISFTPConnection::RealPath ( [in] BSTR original,
[out, retval] BSTR * retval )

Resolves a relative or symbolic path into its canonical absolute equivalent on the server.

The Operation: This method sends an SSH_FXP_REALPATH request. It is the most reliable way to determine the "Home" directory or to expand relative paths into the absolute paths required by methods like DownloadFile.

Key Use Cases:

  • Home Directory: Pass . or an empty string to discover the user's starting path.
  • Normalization: Converts /home/user/../etc/./passwd into /etc/passwd.
  • Link Resolution: Resolves symbolic links to their literal targets.
Parameters
[in]originalThe path string to resolve (e.g., ".", "..", or a symlink).
[out]retvalReceives the resolved absolute path string.

◆ RealPathEx()

HRESULT ISFTPConnection::RealPathEx ( [in] BSTR original,
[in] long flags,
[in] BSTR component,
[out, retval] BSTR * retval )

An extended path resolution method supporting SFTP v6 control flags.

Advanced Resolution: This version corresponds to the expanded SSH_FXP_REALPATH request introduced in later SFTP protocol versions (v6). It allows for more granular control over how the server processes the path.

Automatic Fallback: If the connected server uses an SFTP protocol version lower than 6 (such as the common SFTP v3), this method automatically falls back to the standard RealPath behavior. In this scenario, the flags and component parameters are ignored, and the method resolves the original path string using the baseline protocol functionality.

Parameters:

  • flags: Controls the resolution behavior. Common values include:
  • SSH_FXP_REALPATH_NO_CHECK (0x00000001): Return the path even if it doesn't exist.
  • SSH_FXP_REALPATH_STAT_IF_EXISTS (0x00000002): Returns attributes if the path is valid.
  • SSH_FXP_REALPATH_STAT_ALWAYS (0x00000003): Fail if the path doesn't exist.
  • component: Used for resolving a base path plus a relative component in one round trip, reducing network latency.
Parameters
[in]originalThe base path to be resolved.
[in]flagsControl flags from the SFTP v6 specification.
[in]componentAn optional additional path component to append and resolve against the original path.
[out]retvalReceives the resulting canonical path.

◆ RemoveDirectory()

HRESULT ISFTPConnection::RemoveDirectory ( [in] BSTR directory)

Deletes an empty directory from the remote server.

The Operation: This method sends an SSH_FXP_RMDIR request to the server.

Strict Requirements:

  • Must be Empty: According to the SFTP protocol standard, most servers will only allow you to remove a directory if it contains no files and no subdirectories (other than the standard . and .. entries).

Recursive Deletion: This method does not perform a recursive delete. If you need to remove a directory tree, you must first recursively delete all files using RemoveFile and subdirectories using RemoveDirectory in a bottom-up approach.

Parameters
[in]directoryThe full absolute path of the empty directory to delete.

◆ RemoveFile()

HRESULT ISFTPConnection::RemoveFile ( [in] BSTR file)

Deletes a specific file from the remote server.

The Operation: This method sends an SSH_FXP_REMOVE request to the server. It is specifically designed for regular files and symbolic links.

Parameters
[in]fileThe full absolute path of the file to be deleted.

◆ Rename()

HRESULT ISFTPConnection::Rename ( [in] BSTR oldPath,
[in] BSTR newPath,
[in] long flags )

Renames or moves a file/directory on the remote server.

The Operation: This method sends an SSH_FXP_RENAME request to the server. It effectively works as a "Move" command—you can rename a file within the same directory or move it to a completely different directory path.

The Flags: The flags parameter directly maps to the SSH_FXP_RENAME packet flags defined in SFTP version 5 (and supported by OpenSSH via the posix-rename@openssh.com extension).

Common values include:

  • 0x00000000 (Default): A simple rename. Fails if newPath already exists.
  • 0x00000001 (SSH_FXF_RENAME_OVERWRITE): Silently overwrites newPath if it exists.
  • 0x00000002 (SSH_FXF_RENAME_ATOMIC): Ensures the rename is atomic (all-or-nothing). This is crucial for replacing configuration files or updating executables while they are in use. Note: Atomic implies Overwrite.
  • 0x00000004 (SSH_FXF_RENAME_NATIVE): Performs a native OS rename operation.

Protocol Compatibility:

  • SFTP v3 (Standard): The original protocol does not support flags. If you pass 0, it uses standard behavior (fail if exists).
  • SFTP v3 (OpenSSH): If you pass non-zero flags, the component typically attempts to use the posix-rename@openssh.com extension.
  • SFTP v5+: The flags are sent natively.
Parameters
[in]oldPathThe full absolute path of the existing file/directory.
[in]newPathThe full absolute path of the new name/location.
[in]flagsA bitmask controlling the rename behavior (e.g., 1 for Overwrite, 2 for Atomic).

◆ SetFileLogger()

HRESULT ISFTPConnection::SetFileLogger ( [out, retval] IFileLogger ** fileLogger)

Creates a file logger sfFTPLib::FileLogger and attaches it to the Logger property.

Warning: * Calling this method a second time will detach and destroy the previous logger, replacing it with a new, unconfigured instance.

Typical Usage Workflow:

  1. Call SetFileLogger to get the interface.
  2. Set the log file path (e.g., File = c:\logs\ssh.log) on the returned object.
  3. Call Connect.
Parameters
[out]fileLoggerReceives the pointer to the newly created and attached IFileLogger interface.

◆ SetStat()

HRESULT ISFTPConnection::SetStat ( [in] BSTR path,
[in] IFTPItem * item )

Updates the attributes of a remote file or directory.

The Operation: This method sends an SSH_FXP_SETSTAT request to the server. It takes the attributes stored within the provided IFTPItem and applies them to the object at the specified path.

Modifiable Attributes: While an IFTPItem contains many properties, SetStat is typically used to update:

  • Permissions: Unix-style mode (e.g., changing a file to read-only or making a script executable).
  • Timestamps: Last Access Time and Last Modification Time.
  • Ownership: User ID (UID) and Group ID (GID), provided the authenticated user has sufficient privileges.
Parameters
[in]pathThe full absolute path to the remote file or directory.
[in]itemAn IFTPItem object containing the attribute values to be applied.

◆ Stat()

HRESULT ISFTPConnection::Stat ( [in] BSTR path,
[in] long flags,
[out, retval] IFTPItem ** retval )

Retrieves information and attributes for a file or directory.

The Operation: Sends an SSH_FXP_STAT request. If the path refers to a symbolic link, the server follows the link and returns the attributes of the target file or directory.

Parameters
[in]pathThe full absolute path to the remote object.
[in]flagsA bitmask of sfFTPLib::SFTPItemAttribute (SFTP v4+) indicating which attributes are requested. For SFTP v3, this is typically ignored as the server returns all available attributes.
[out]retvalReceives an IFTPItem containing the metadata.

◆ StatEx()

HRESULT ISFTPConnection::StatEx ( [in] BSTR path,
[in] long flags,
VARIANT_BOOL followLink,
[out, retval] IFTPItem ** retval )

An extended attribute retrieval method with explicit symbolic link control.

This method provides a unified interface for both Stat and LStat behaviors.

Parameters
[in]pathThe full absolute path to the remote object.
[in]flagsA bitmask of sfFTPLib::SFTPItemAttribute (SFTP v4+) indicating which attributes are requested.
[in]followLink
  • VARIANT_TRUE: Behaves like Stat (follows symlinks).
  • VARIANT_FALSE: Behaves like LStat (describes the link itself).
[out]retvalReceives the IFTPItem interface.

◆ StatVFS()

HRESULT ISFTPConnection::StatVFS ( [in] BSTR path,
[out, retval] ISFTPStatVFS ** retval )

Retrieves information about the remote file system's capacity and limits.

The Operation: This method utilizes the statvfs@openssh.com extension (or the native SFTP v6 SSH_FXP_FSTATVFS functionality) to query the server about the file system containing the specified path.

The Return Value: Returns an ISFTPStatVFS interface. This object is a snapshot of the file system's state at the moment the call was made.

Parameters
[in]pathAny valid absolute path on the target file system.
[out]retvalReceives a pointer to an ISFTPStatVFS object populated with the file system stats.

◆ UploadFile()

HRESULT ISFTPConnection::UploadFile ( [in] VARIANT localFile,
[in] BSTR remoteFile,
[in] DataTransferType transferType,
[in] long startPositionLo,
[in] long startPositionHi )

Transfers a file or stream from the local system to the remote server.

The Operation: This method initiates an upload sequence:

  1. Opens the remoteFile on the server using SSH_FXP_OPEN (with Create/Write flags).
  2. Seeks the remote file handle to startPosition (for resuming or appending).
  3. Reads data from localFile (disk or stream).
  4. Writes data to the server in chunks (typically 32KB - 64KB) via SSH_FXP_WRITE.

Flexible Source (localFile): The localFile parameter is a VARIANT that accepts two types of input:

  • String (BSTR): The full path to a file on the local disk.
  • Object (IStream*): A COM interface pointer to a readable stream. This allows you to upload data generated in memory, from a database, or from another network stream without saving to disk first.

Resuming Transfers: To resume a broken upload, pass the current size of the remote file as the start position. The 64-bit offset is split into two 32-bit integers: Offset = (startPositionHi * 2^32) + startPositionLo

Parameters
[in]localFileThe source: either a local file path (String) or a readable COM stream (IStream).
[in]remoteFileThe full absolute path where the file should be saved on the server.
[in]transferTypeThe mode of transfer defined by the DataTransferType enum (Binary, ASCII, etc.).
[in]startPositionLoThe lower 32 bits of the remote starting byte offset (Resume/Append position).
[in]startPositionHiThe upper 32 bits of the remote starting byte offset.

◆ UploadFileEx()

HRESULT ISFTPConnection::UploadFileEx ( [in] VARIANT localFile,
[in] BSTR remoteFile,
[in] DataTransferType transferType,
[in] ULONGLONG startPosition,
[in] ITransferProgressEvents * progress )

An advanced method to upload data to the remote server with progress tracking.

The "Extended" Capabilities: Unlike the standard UploadFile, this method offers:

  1. Native 64-bit: Uses ULONGLONG directly for the offset, simplifying large file support.
  2. Event Callbacks: Accepts an ITransferProgressEvents interface to report granular progress to the user interface.

Usage Scenarios:

  • Appending Logs: Set startPosition to the remote file's current size to append new log entries from a local stream.
  • Resuming: If a previous upload failed at 50MB, set startPosition to 50MB (52,428,800 bytes) to continue where it left off.
Parameters
[in]localFileThe source: either a local file path (String) or a readable COM stream (IStream).
[in]remoteFileThe full absolute path where the file should be saved on the server.
[in]transferTypeThe mode of transfer defined by the DataTransferType enum.
[in]startPositionThe byte offset in the remote file at which to begin writing. 0 overwrites from the beginning.
[in]progressA pointer to an implementation of ITransferProgressEvents. The component will call ITransferProgressEvents::OnTransferProgress during the transfer. Pass NULL if monitoring is not required.

Property Documentation

◆ Busy

VARIANT_BOOL ISFTPConnection::Busy
getproperty

Indicates whether the connection is currently executing an operation.

◆ CodePage

long ISFTPConnection::CodePage
getsetproperty

Specifies the character encoding used to interpret filenames on the remote server.

The Problem: SFTP servers store filenames as sequences of bytes. To display these names in your application (which uses Unicode/BSTR), the component must translate those bytes into characters. If the wrong encoding is used, filenames will appear corrupted (mojibake).

Default Value: The default setting is 65001 (UTF-8). This aligns with modern SFTP standards and the behavior of most Linux-based servers and OpenSSH.

Protocol differences:

  • SFTP v4, v5, v6: The protocol mandates UTF-8. In these versions, this property is ignored or automatically locked to 65001 (UTF-8).
  • SFTP v3 (OpenSSH): The protocol treats filenames as raw byte strings. While modern OpenSSH servers use UTF-8, legacy servers or older Windows-based SFTP v3 servers may use local code pages (e.g., Windows-1252).

Common Values:

  • 65001 (UTF-8): (Default) The standard for almost all modern servers (Linux, macOS, OpenSSH).
  • 0 (CP_ACP): Uses the local system's default ANSI code page.
  • 1252: Western European (legacy Windows).
  • 932: Shift-JIS (legacy Japanese systems).

When to change this: If you connect to a server and filenames appear with "garbage" characters (e.g., é instead of é\endiskip), the server is likely using a legacy local code page instead of UTF-8. Adjusting this value corrects the display without changing the actual data on the server.

Parameters
[in]newValueThe numeric identifier of the code page (e.g., 65001, 1252, 0).
[out]retvalReceives the current code page setting.

◆ LastStatusCode

SFTPStatus ISFTPConnection::LastStatusCode
getproperty

Retrieves the most recent protocol-level status code returned by the SFTP server.

The Context: When an SFTP operation fails, the standard COM return value (HRESULT) is often a generic error code (like E_FAIL or 0x8004xxxx). To understand the specific reason for the failure (e.g., "File not found" vs. "Permission denied"), you must check this property.

Persistence: This value is updated after every SFTP command. It retains the status of the last * executed command until a new command is issued.

Parameters
[out]retvalReceives the SFTPStatus enum value of the last operation (e.g., ftpSFTPStatusOk if successful).

◆ LastStatusMessage

BSTR ISFTPConnection::LastStatusMessage
getproperty

Retrieves the human-readable error message returned by the SFTP server for the last operation.

The Source: When an SFTP server sends a status response (e.g., SSH_FXP_STATUS), it includes both a numeric error code and a text message string. This property exposes that text string.

Usage: Use this property for logging and user feedback.

  • While LastStatusCode gives you the category (e.g., "Permission Denied"), LastStatusMessage often provides the specific context (e.g., "Access denied for user 'bob': group write permission missing").

Localization: The language of this message is determined by the server's configuration and the language tag sent in the initial version negotiation. However, most servers default to English.

Parameters
[out]retvalReceives the error message string (e.g., "File not found" or "Success").

◆ LastTransferBytes

ULONGLONG ISFTPConnection::LastTransferBytes
getproperty

Retrieves the total number of bytes transferred during the last SFTP transfer.

The Scope: This value represents the payload size successfully sent or received in the most recent file transfer (upload or download) or directory listing. It resets at the start of each new transfer.

Parameters
[out]retvalReceives the number of bytes transferred.

◆ LastTransferBytesHi

long ISFTPConnection::LastTransferBytesHi
getproperty

Retrieves the upper 32 bits of the last transfer size.

Legacy Support: This property is provided for languages or environments (like VB6) It represents the LastTransferBytes >> 32.

Calculation: To reconstruct the full 64-bit value manually: (High * 2^32) + Low.

Parameters
[out]retvalReceives the high-order double word of the byte count.

◆ LastTransferBytesLo

long ISFTPConnection::LastTransferBytesLo
getproperty

Retrieves the lower 32 bits of the last transfer size.

Legacy Support: This property is provided for languages or environments (like VB6) that do not natively support 64-bit integers. It represents the LastTransferBytes & 0xFFFFFFFF.

Parameters
[out]retvalReceives the low-order double word of the byte count.

◆ LastTransferSpeed

long ISFTPConnection::LastTransferSpeed
getproperty

Retrieves the average data transfer rate of the last SFTP transfer.

The Calculation: This value is derived automatically from LastTransferBytes and LastTransferTime. It represents the average speed over the entire duration of the operation.

Speed = LastTransferBytes / (LastTransferTime / 1000)

Edge Cases: If the transfer time was effectively zero (e.g., extremely small files < 1KB), this property returns 0 to avoid division-by-zero errors.

Parameters
[out]retvalReceives the transfer speed in Bytes per second.

◆ LastTransferTime

long ISFTPConnection::LastTransferTime
getproperty

Retrieves the duration of the last SFTP transfer in milliseconds.

The Measurement: This value represents the elapsed wall-clock time from the start of the request to the receipt of the final response (or error). It applies to file transfers (upload/download), and directory listings.

Parameters
[out]retvalReceives the elapsed time in milliseconds (e.g., 1500 for 1.5 seconds).

◆ Logger

ILogger ISFTPConnection::Logger
setproperty

Attaches a logging mechanism to the SFTP session for debugging and auditing.

This property allows you to capture the internal activity of the component. By assigning an object that implements the ILogger interface, you can redirect log messages to a file, the console, or a custom monitoring system.

See also
sfFTPLib::FileLogger
Parameters
[in]loggerA pointer to an ILogger implementation. Set to NULL to disable logging.

◆ ProtocolVersion

long ISFTPConnection::ProtocolVersion
getproperty

Retrieves the SFTP protocol version currently in use for the active session.

The Negotiation Outcome: After the SFTP subsystem is initialized, this property contains the result of the version exchange. This is the highest version supported by both the client and the server, limited by the ProtocolVersionPreference.

Parameters
[out]retvalReceives the negotiated SFTP protocol version (e.g., 3, 4, 5, or 6).

◆ ProtocolVersionPreference

long ISFTPConnection::ProtocolVersionPreference
getsetproperty

Controls the preferred version of the SFTP protocol to negotiate with the server.

The Protocol Versions: SFTP has evolved through several protocol iterations (drafts). This property allows you to limit or prefer specific versions to ensure compatibility with various server implementations.

  • Version 3: The most widely compatible version (supported by OpenSSH). It provides core file operations but lacks standardized error codes and advanced attribute handling.
  • Version 4-6: Later drafts that introduced improved character encoding (UTF-8), better file attribute support (ACLs), and more granular error reporting.

The Negotiation Logic: During the SFTP subsystem initialization, the client and server exchange their highest supported versions. The connection will proceed using the highest version supported by both parties, capped by this preference value.

Common Compatibility Notes:

  • OpenSSH: Strictly supports SFTP v3. Setting this to a higher value will still result in a v3 connection when connecting to an OpenSSH server.
  • Commercial Servers: Many enterprise servers (like Tectia or Bitvise) support versions 4 through 6.
Parameters
[in]newValueThe maximum SFTP version to allow (e.g., 3, 4, 5, or 6). Default is 6
[out]retvalReceives the current version preference.

◆ ServerLineTerminator

BSTR ISFTPConnection::ServerLineTerminator
getsetproperty

Specifies the line ending sequence used by the remote server for text-based operations.

The Problem: Different operating systems use different characters to represent the end of a line in text files. If these are not handled correctly during transfer, files may appear as a single long line or contain "garbage" characters (like ^M) when opened on the target system.

Common Sequences:

  • **\n (LF):** Standard for Unix, Linux, and modern macOS.
  • **\r\n (CRLF):** Standard for Windows and DOS.
  • **\r (CR):** Used by legacy classic Mac OS (pre-OS X).

The Solution: When performing ASCII/Text mode transfers, the component uses this property to identify where lines end on the server. It then performs the necessary translation to match the local system's line terminator (\r\n).

The Default (
):
By default, this property is set to \n, as the vast majority of SSH/SFTP servers are hosted on Unix-like environments.

Parameters
[in]newValueA string containing the character sequence representing a newline on the server (e.g., "\n" or "\r\n").
[out]retvalReceives the currently configured server line terminator string.

◆ ServerState

ISFTPServerState ISFTPConnection::ServerState
getproperty

Accesses the read-only object describing the capabilities and identity of the connected SFTP server.

Upon a successful connection, the component populates this object with all the metadata provided by the server during the Protocol Version Exchange (SSH_FXP_VERSION).

Parameters
[out]retvalReceives the ISFTPServerState interface pointer.

◆ SFTPServerCommand

BSTR ISFTPConnection::SFTPServerCommand
getsetproperty

Specifies the command or subsystem name used to initialize the SFTP session on the remote server.

The Default (Empty): By default, this property is an empty string. In this state, the component sends a standard SSH subsystem request for "sftp". This is the recommended setting for 99% of connections, as it allows the server to launch its configured SFTP handler (RFC 4253).

When to Change It: You should set this property to a specific string if you need to override the default behavior:

  1. Privilege Elevation (sudo): If you need to access files as root, you can set this to a command string like sudo /usr/lib/openssh/sftp-server.
  2. Non-Standard Paths: If the server does not have sftp in its system PATH or sshd_config, you can specify the absolute path, e.g., /usr/local/bin/sftp-server.
  3. Custom Flags: To enable server-side logging or read-only mode, e.g., /usr/libexec/sftp-server -l INFO -f AUTH.

Mechanism:

  • Empty: Sends an SSH subsystem request for "sftp".
  • Non-Empty: Sends an SSH exec request to run the specific command line provided.
Parameters
[in]newValueThe command string to execute. Leave empty for standard behavior.
[out]retvalReceives the current server command setting.

◆ SSHConnection

ISSHConnection ISFTPConnection::SSHConnection
getproperty

Accesses the underlying Secure Shell (SSH) transport interface.

Parameters
[out]retvalReceives the address of the ISSHConnection interface pointer.

◆ Status

SFTPConnectionStatus ISFTPConnection::Status
getproperty

Retrieves the current operational state of the SFTP subsystem.

This property tracks the lifecycle of the SFTP channel specifically. It is distinct from the underlying SSH transport state. It is possible for the SSH connection to be active while the SFTP subsystem is still initializing or has failed to start.

Parameters
[out]retvalReceives the current SFTPConnectionStatus enum value.

◆ Timeout

long ISFTPConnection::Timeout
getsetproperty

Sets the maximum time (in seconds) to wait for a network operation to complete.

This property defines the timeout threshold for all blocking calls, such as connecting, reading data, or waiting for a server response. If an operation exceeds this duration, it is aborted and returns an error.

Default:

  • The default value is 30 (30 seconds).
Parameters
[in]newValueThe timeout duration in seconds.
[out]retvalReceives the current timeout setting.

◆ UseMessageLoop

VARIANT_BOOL ISFTPConnection::UseMessageLoop
getsetproperty

Controls whether the component processes Windows messages during blocking operations.

This property determines how the library behaves while waiting for a network response.

Settings:

  • VARIANT_FALSE (Default): The calling thread is put to sleep until the operation completes.
  • Pros: Higher performance, no re-entrancy risks.
  • Cons: The application UI will freeze and be marked as "Not Responding" by Windows during long transfers.
  • VARIANT_TRUE: The library pumps the Windows Message Queue while waiting.
  • Pros: The UI remains responsive (repaints, moves, minimizes).
  • Cons: Slower performance. Risk of Re-entrancy: Users might click a "Connect" button again while the first connection is still in progress.

When to use TRUE: Enable this if you are using the component on the Main UI Thread of a desktop application (VB6, VBA, Delphi, WinForms) and want to keep the window responsive.

When to use FALSE: Keep this disabled for Console apps, Windows Services, or background worker threads where no UI interaction exists.

Parameters
[in]newValueSet to VARIANT_TRUE to enable message pumping; VARIANT_FALSE to disable it.
[out]retvalReceives the current setting.

◆ VendorId

ISFTPVendorId ISFTPConnection::VendorId
getsetproperty

Configures the software identification data that the client sends to the server.

The Purpose: This property allows you to customize the "Client Vendor ID" information transmitted to the server during the SFTP version negotiation (SSH_FXP_INIT).

To Get Server Info: To see the Vendor ID sent by the server, you must inspect the ISFTPServerState::VendorId property after the connection is established.

Parameters
[in]newValueThe ISFTPVendorId object containing the client identification to send.
[out]retvalReceives the currently configured client identification object.

The documentation for this interface was generated from the following file: