Documentation
¶
Overview ¶
Package sftp implements the SSH File Transfer Protocol as described in https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt
Index ¶
- Constants
- Variables
- func FileInfoFromStat(stat *FileStat, name string) os.FileInfo
- type AsyncFunc
- type Client
- func (client *Client) Chmod(pathN string, mode os.FileMode) error
- func (client *Client) Chown(pathN string, uid, gid int) error
- func (client *Client) Chtimes(pathN string, atime time.Time, mtime time.Time) error
- func (client *Client) Close() error
- func (client *Client) Create(pathN string) (*File, error)
- func (client *Client) CreateAsync(pathN string, req any, onComplete AsyncFunc) (f *File, err error)
- func (client *Client) FS() fs.FS
- func (client *Client) Getwd() (string, error)
- func (c *Client) Glob(pattern string) (matches []string, err error)
- func (client *Client) HasExtension(name string) (string, bool)
- func (client *Client) HasPosixRename() (yes bool)
- func (client *Client) HasStatVFS() (yes bool)
- func (client *Client) Link(oldname, newname string) error
- func (client *Client) Lstat(pathN string) (attrs *FileStat, err error)
- func (client *Client) Mkdir(dirN string) error
- func (client *Client) MkdirAll(dirN string) (err error)
- func (client *Client) Open(pathN string, flags int) (*File, error)
- func (client *Client) OpenAsync(pathN string, flags int, req any, onComplete AsyncFunc) (f *File, err error)
- func (client *Client) OpenRead(pathN string) (*File, error)
- func (client *Client) OpenReadAsync(pathN string, req any, onComplete AsyncFunc) (f *File, err error)
- func (client *Client) PosixRename(oldN, newN string) error
- func (client *Client) PosixRenameAsync(oldN, newN string, req any, onComplete AsyncFunc) (err error)
- func (client *Client) ReadDir(dirN string) ([]*File, error)
- func (client *Client) ReadDirLimit(dirN string, timeout time.Duration, filter ReadDirFilter, entries []*File) (rv []*File, err error)
- func (client *Client) ReadLink(pathN string) (target string, err error)
- func (client *Client) RealPath(pathN string) (canonN string, err error)
- func (client *Client) Remove(pathN string) error
- func (client *Client) RemoveAll(dirN string) (err error)
- func (client *Client) RemoveAllIn(dirN string) (err error)
- func (client *Client) RemoveAsync(pathN string, req any, onComplete AsyncFunc) error
- func (client *Client) RemoveDirectory(pathN string) error
- func (client *Client) Rename(oldN, newN string) error
- func (client *Client) RenameAsync(oldN, newN string, req any, onComplete AsyncFunc) (err error)
- func (client *Client) SetExtendedAttr(pathN string, ext []StatExtended) error
- func (client *Client) Stat(pathN string) (fs *FileStat, err error)
- func (client *Client) StatVFS(pathN string) (rv *StatVFS, err error)
- func (client *Client) StatVFS2(pathN string, rv *StatVFS) (err error)
- func (client *Client) Symlink(oldname, newname string) error
- func (client *Client) Truncate(pathN string, size int64) error
- func (client *Client) WalkDir(rootD string, f fs.WalkDirFunc) error
- type ClientOption
- type FS
- type File
- func (f *File) AttrsCached() bool
- func (f *File) BaseName() string
- func (f *File) Chmod(mode os.FileMode) error
- func (f *File) Chown(uid, gid int) error
- func (f *File) Client() *Client
- func (f *File) Close() error
- func (f *File) CloseAsync(req any, onComplete AsyncFunc) error
- func (f *File) FileStat() FileStat
- func (f *File) IsDir() bool
- func (f *File) IsOpen() bool
- func (f *File) IsRegular() bool
- func (f *File) ModTime() time.Time
- func (f *File) ModTimeUnix() uint32
- func (f *File) Mode() FileMode
- func (f *File) Name() string
- func (f *File) Open(flags int) (err error)
- func (f *File) OpenAsync(flags int, req any, onComplete AsyncFunc) (err error)
- func (f *File) OpenRead() (err error)
- func (f *File) OpenReadAsync(req any, onComplete AsyncFunc) (err error)
- func (f *File) OsFileInfo() os.FileInfo
- func (f *File) OsFileMode() os.FileMode
- func (f *File) PosixRename(newN string) (err error)
- func (f *File) PosixRenameAsync(newN string, req any, onComplete AsyncFunc) error
- func (f *File) Read(b []byte) (nread int, err error)
- func (f *File) ReadAt(toBuff []byte, offset int64) (nread int, err error)
- func (f *File) ReadFrom(fromR io.Reader) (nread int64, err error)
- func (f *File) Remove() (err error)
- func (f *File) RemoveAsync(req any, onComplete AsyncFunc) error
- func (f *File) Rename(newN string) (err error)
- func (f *File) RenameAsync(newN string, req any, onComplete AsyncFunc) error
- func (f *File) Seek(offset int64, whence int) (int64, error)
- func (f *File) SetClient(c *Client) error
- func (f *File) SetExtendedData(path string, extended []StatExtended) error
- func (f *File) SetName(newN string)
- func (f *File) Size() uint64
- func (f *File) Stat() (attrs *FileStat, err error)
- func (f *File) Sync() error
- func (f *File) SyncAsync(req any, onComplete AsyncFunc) error
- func (f *File) Truncate(size int64) error
- func (f *File) Write(b []byte) (nwrote int, err error)
- func (f *File) WriteAt(dataB []byte, offset int64) (written int, err error)
- func (f *File) WriteTo(w io.Writer) (written int64, err error)
- type FileInfoExtendedData
- type FileInfoUidGid
- type FileMode
- type FileStat
- func (fs *FileStat) AccessTime() time.Time
- func (fs *FileStat) AsFileInfo(name string) os.FileInfo
- func (fs *FileStat) FileMode() FileMode
- func (fs *FileStat) FileType() FileMode
- func (fs *FileStat) IsDir() bool
- func (fs *FileStat) IsRegular() bool
- func (fs *FileStat) ModTime() time.Time
- func (fs *FileStat) OsFileMode() os.FileMode
- type ReadDirFilter
- type ReadDirLimit
- type StatExtended
- type StatStrategy
- type StatVFS
- type StatusError
Constants ¶
const ( ErrSSHFxOk = fxerr(sshFxOk) ErrSSHFxEOF = fxerr(sshFxEOF) ErrSSHFxNoSuchFile = fxerr(sshFxNoSuchFile) ErrSSHFxPermissionDenied = fxerr(sshFxPermissionDenied) ErrSSHFxFailure = fxerr(sshFxFailure) ErrSSHFxBadMessage = fxerr(sshFxBadMessage) ErrSSHFxNoConnection = fxerr(sshFxNoConnection) ErrSSHFxConnectionLost = fxerr(sshFxConnectionLost) ErrSSHFxOpUnsupported = fxerr(sshFxOPUnsupported) )
Error types that match the SFTP's SSH_FXP_STATUS codes. Gives you more direct control of the errors being sent vs. letting the library work them out from the standard os/io errors.
const ErrOpenned = uerr.Const("file already openned")
const S_IFMT = uint32(ModeType)
S_IFMT is a legacy export, and was brought in to support GOOS environments whose sysconfig.S_IFMT may be different from the value used internally by SFTP standards. There should be no reason why you need to import it, or use it, but unexporting it could cause code to break in a way that cannot be readily fixed. As such, we continue to export this value as the value used in the SFTP standard.
Deprecated: Remove use of this value, and avoid any future use as well. There is no alternative provided, you should never need to access this value.
Variables ¶
var ErrBadPattern = path.ErrBadPattern
ErrBadPattern indicates a globbing pattern was malformed.
Functions ¶
Types ¶
type AsyncFunc ¶
Callback invoked upon completion of an async operation.
This is useful to avoid waiting for responses before starting the next operation. For example, a pipeline where a file is opened async, could feed a chan to a worker that then writes to the open file and async closes it, which then feeds a chan for a worker that gets the close disposition.
Any work performed in the callback should be brief and non blocking, offloading any time consuming or blocking work to a separate goroutine. This callback will be called in the event loop of the connection reader, so delaying return delays reading the next message.
If nil, then the async operation is "fire and forget". This is useful (for example) after closing a File that is open for reading, but dangerous (for example) after closing a file that is open for writing.
The req is provided by the caller as "callback data".
The error is the disposition of the async operation. If nil, then the operation was successful.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents an SFTP session on a *ssh.ClientConn SSH connection. Multiple Clients can be active on a single SSH connection, and a Client may be called concurrently from multiple Goroutines.
func NewClient ¶
func NewClient(conn *ssh.Client, opts ...ClientOption) (rv *Client, err error)
Create a new SFTP client on the SSH client conn
func NewClientPipe ¶
func NewClientPipe( rd io.Reader, wr io.WriteCloser, opts ...ClientOption, ) ( client *Client, err error, )
Create a new SFTP client with the Reader and a WriteCloser. This can be used for connecting to an SFTP server over TCP/TLS or by using the system's ssh client program (e.g. via exec.Command).
func (*Client) Chmod ¶
Change the permissions of the named file.
No umask will be applied. Because even retrieving the umask is not possible in a portable way without causing a race condition. Callers should mask off umask bits, if desired.
func (*Client) Create ¶
Create the named file mode 0666 (before umask), truncating it if it already exists. If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If you need more control over the flags/mode used to open the file see client.OpenFile.
Note that some SFTP servers (eg. AWS Transfer) do not support opening files read/write at the same time. For those services you will need to use `client.OpenFile(os.O_WRONLY|os.O_CREATE|os.O_TRUNC)`.
func (*Client) CreateAsync ¶
func (client *Client) CreateAsync( pathN string, req any, onComplete AsyncFunc, ) (f *File, err error)
Create the file, async.
func (*Client) Getwd ¶
Return the current working directory of the server. Operations involving relative paths will be based at this location.
func (*Client) Glob ¶
Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in Match. The pattern may describe hierarchical names such as /usr/*/bin/ed.
Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is ErrBadPattern, when pattern is malformed.
func (*Client) HasExtension ¶
Check whether the server supports a named extension.
The first return value is the extension data reported by the server (typically a version number).
func (*Client) HasPosixRename ¶
does server support PosixRename?
func (*Client) HasStatVFS ¶
does server support StatVFS?
func (*Client) Link ¶
Link creates a hard link at 'newname', pointing at the same inode as 'oldname'
func (*Client) Lstat ¶
Return a FileStat describing the file specified by pathN. If pathN is a symbolic link, the returned FileStat describes the link, not the actual file.
func (*Client) Mkdir ¶
Create the specified directory. An error will be returned if a file or directory with the specified path already exists, or if the directory's parent folder does not exist (the method cannot create complete paths).
func (*Client) MkdirAll ¶
Create the dirN directory, along with any necessary parents. If dirN exists and is a directory, do nothing and return nil. If dirN exists and is not a directory, return error.
func (*Client) OpenAsync ¶
func (client *Client) OpenAsync( pathN string, flags int, req any, onComplete AsyncFunc, ) (f *File, err error)
Open file at path using the specified flags, async
func (*Client) OpenReadAsync ¶
func (client *Client) OpenReadAsync( pathN string, req any, onComplete AsyncFunc, ) (f *File, err error)
Open file at pathN for reading, async.
func (*Client) PosixRename ¶
Rename oldN to newN, replacing newN if it exists. Uses the posix-rename@openssh.com extension.
func (*Client) PosixRenameAsync ¶
func (client *Client) PosixRenameAsync( oldN, newN string, req any, onComplete AsyncFunc, ) (err error)
Rename oldN to newN, replacing newN if it exists, async. Uses the posix-rename@openssh.com extension.
func (*Client) ReadDir ¶
Get a list of Files in dirN.
Due to SFTP, it takes at least 3 round trips with the server to get a listing of the files.
func (*Client) ReadDirLimit ¶
func (client *Client) ReadDirLimit( dirN string, timeout time.Duration, filter ReadDirFilter, entries []*File, ) ( rv []*File, err error, )
Get a list of Files in dirN.
Due to SFTP, it takes at least 3 round trips with the server to get a listing of the files.
func (*Client) RealPath ¶
Request server to canonicalize pathN to an absolute path.
This is useful for converting path names containing ".." components, or relative pathnames without a leading slash into absolute paths.
func (*Client) Remove ¶
Remove pathN. Return error if pathN does not exist, or if pathN is a non-empty directory.
func (*Client) RemoveAll ¶
Delete dirN and all files (if dirN is a dir) of any kind contained in dirN.
This will error if dirN does not exist.
func (*Client) RemoveAllIn ¶
Delete all files contained in dirN, but do not delete dirN.
func (*Client) RemoveAsync ¶
func (*Client) RemoveDirectory ¶
RemoveDirectory removes a directory path.
func (*Client) RenameAsync ¶
Rename oldN to newN, async.
func (*Client) SetExtendedAttr ¶
func (client *Client) SetExtendedAttr(pathN string, ext []StatExtended) error
Set extended attributes of the named file, using the SSH_FILEXFER_ATTR_EXTENDED flag in the setstat request.
This flag provides a general extension mechanism for vendor-specific extensions. Names of the attributes should be a string of the format "name@domain", where "domain" is a valid, registered domain name and "name" identifies the method. Server implementations SHOULD ignore extended data fields that they do not understand.
func (*Client) Stat ¶
Return a FileStat describing the file specified by pathN If pathN is a symbolic link, the returned FileStat describes the actual file, not the link.
func (*Client) StatVFS ¶
get VFS (file system) statistics from a remote host.
Implement the statvfs@openssh.com SSH_FXP_EXTENDED feature from http://www.opensource.apple.com/source/OpenSSH/OpenSSH-175/openssh/PROTOCOL?txt.
func (*Client) StatVFS2 ¶
get VFS (file system) statistics from a remote host, less allocation.
Implement the statvfs@openssh.com SSH_FXP_EXTENDED feature from http://www.opensource.apple.com/source/OpenSSH/OpenSSH-175/openssh/PROTOCOL?txt.
type ClientOption ¶
A ClientOption is a function which applies configuration to a Client.
func WithErrorFunc ¶
func WithErrorFunc(onError func(error)) ClientOption
Add a func to receive async error notifications. These can occur if the connection to the SFTP server is lost, for example.
The func should not perform time consuming operations. One or more invocations may occur on connection failure.
func WithMaxPacket ¶
func WithMaxPacket(size int) ClientOption
Set the maximum size (bytes) of the payload.
The larger the payload, the more efficient the transport.
The default is 32768 (32KiB), which all compliant SFTP servers must support. - OpenSsh supports 255KiB (version 8.7 was used for the test)
If you get the error "failed to send packet header: EOF" when copying a large file, try lowering this number.
func WithStatStrategy ¶
func WithStatStrategy(strategy StatStrategy) ClientOption
Specify what File.WriteTo, File.Read, File.ReadAt, File.Seek should do to determine the File size. Default is LazyStat.
type File ¶
type File struct { Stash any // stash whatever you want here // contains filtered or unexported fields }
Provide access to a remote file.
Files obtained via Client.ReadDir are not in an open state. They must be opened first. These Files do have populated attributes.
Files obtained via Client.Open calls are open, but do not have populated attributes until Stat() is called.
Calls that change the offset (Read/ReadFrom/Write/WriteTo/Seek) need to be externally coordinated or synchronized. This is no different than dealing with any other kind of file, as concurrent reads and writes will result in gibberish otherwise.
Likewise, Open/Close needs to also be externally coordinated or synchronized with other i/o ops.
func (*File) AttrsCached ¶
return true if attributes are populated
func (*File) CloseAsync ¶
close the File, async.
Use nil for request and respC to "fire and forget". This is useful when closing after an error encountered or for done reading, but dangerous after a successful write, as it is possible the write is not 100% complete and a failure is detected during close.
syncronize access
func (*File) FileStat ¶
return cached FileStat, which may not be populated with file attributes.
if Mode bits are zero, then it is not populated.
it will be populated after a ReadDir, or a Stat call
func (*File) ModTimeUnix ¶
if attrs are populated, mod time in unix serespConds
it's only 32 bits, but it's unsigned so will not fail in 2038
func (*File) OsFileInfo ¶
return the internal FileStat to a go os.FileInfo
func (*File) OsFileMode ¶
if attrs are populated, mode bits of file. otherwise, bits are zero.
func (*File) PosixRename ¶
rename file, even if newN already exists (replacing it).
uses the posix-rename@openssh.com extension
synchronize access
func (*File) PosixRenameAsync ¶
rename file, async, even if newN already exists (replacing it).
uses the posix-rename@openssh.com extension
synchronize access
func (*File) Read ¶
implement io.Reader
Reads up to len(b) bytes from the File. It returns the number of bytes read and an error, if any. When Read encounters an error or EOF respCondition after successfully reading n > 0 bytes, it returns the number of bytes read.
The read may be broken up into chunks supported by the server.
If transfering to an io.Writer, use WriteTo for best performance. io.Copy will do this automatically.
This call may cause a Stat call, depending on the Client StatStrategy.
synchronize i/o ops
func (*File) ReadAt ¶
implement io.ReaderAt. Read up to len toBuff bytes from file at current offset, leaving offset unchanged.
This call may cause a Stat call, depending on the Client StatStrategy.
synchronize i/o ops
func (*File) ReadFrom ¶
implement io.ReaderFrom
Copy from io.Reader into this file starting at current offset.
synchronize i/o ops
func (*File) Seek ¶
implement io.Seeker
Set the offset for the next Read or Write. Return the next offset.
Seeking before or after the end of the file is undefined.
Seeking relative to the end will call Stat if file has no cached attributes, otherwise, it will use the cached attributes.
Seeking relative to the end of the file will follow the Client StatStrategy.
synchronize i/o ops
func (*File) SetExtendedData ¶
func (f *File) SetExtendedData(path string, extended []StatExtended) error
SetExtendedData sets extended attributes of the current file. It uses the SSH_FILEXFER_ATTR_EXTENDED flag in the setstat request.
This flag provides a general extension mechanism for vendor-specific extensions. Names of the attributes should be a string of the format "name@domain", where "domain" is a valid, registered domain name and "name" identifies the method. Server implementations SHOULD ignore extended data fields that they do not understand.
async safe
func (*File) Stat ¶
Returns the attributes about the file. If the file is open, then fstat is used, otherwise, stat is used. The attributes cached in this File will be updated. To avoid a round trip with the server, use the already cached FileStat.
synchronize i/o ops
func (*File) Sync ¶
Request a flush of the contents of a File to stable storage.
Sync requires the server to support the fsync@openssh.com extension.
async safe
func (*File) SyncAsync ¶
Asynchronously request a flush of the contents of a File to stable storage.
Requires the server to support the fsync@openssh.com extension.
async safe
func (*File) Truncate ¶
Truncate sets the size of the current file. Although it may be safely assumed that if the size is less than its current size it will be truncated to fit, the SFTP protocol does not specify what behavior the server should do when setting size greater than the current size.
async safe
func (*File) Write ¶
implement io.Writer. Write bytes to file, appending at current offset.
synchronize i/o ops
func (*File) WriteAt ¶
implement io.WriterAt. Write bytes to file at current offset, leaving offset unchanged.
synchronize i/o ops
type FileInfoExtendedData ¶
type FileInfoExtendedData interface { os.FileInfo Extended() []StatExtended }
FileInfoUidGid extends os.FileInfo and adds a callbacks for extended data retrieval.
type FileInfoUidGid ¶
FileInfoUidGid extends os.FileInfo and adds callbacks for Uid and Gid retrieval, as an alternative to *syscall.Stat_t objects on unix systems.
type FileMode ¶
type FileMode uint32
FileMode represents a file’s mode and permission bits. The bits are defined according to POSIX standards, and may not apply to the OS being built for.
const ( ModePerm FileMode = 0o0777 // S_IRWXU | S_IRWXG | S_IRWXO ModeUserRead FileMode = 0o0400 // S_IRUSR ModeUserWrite FileMode = 0o0200 // S_IWUSR ModeUserExec FileMode = 0o0100 // S_IXUSR ModeGroupRead FileMode = 0o0040 // S_IRGRP ModeGroupWrite FileMode = 0o0020 // S_IWGRP ModeGroupExec FileMode = 0o0010 // S_IXGRP ModeOtherRead FileMode = 0o0004 // S_IROTH ModeOtherWrite FileMode = 0o0002 // S_IWOTH ModeOtherExec FileMode = 0o0001 // S_IXOTH ModeSetUID FileMode = 0o4000 // S_ISUID ModeSetGID FileMode = 0o2000 // S_ISGID ModeSticky FileMode = 0o1000 // S_ISVTX ModeType FileMode = 0xF000 // S_IFMT ModeNamedPipe FileMode = 0x1000 // S_IFIFO ModeCharDevice FileMode = 0x2000 // S_IFCHR ModeDir FileMode = 0x4000 // S_IFDIR ModeDevice FileMode = 0x6000 // S_IFBLK ModeRegular FileMode = 0x8000 // S_IFREG ModeSymlink FileMode = 0xA000 // S_IFLNK ModeSocket FileMode = 0xC000 // S_IFSOCK )
Permission flags, defined here to avoid potential inconsistencies in individual OS implementations.
func (FileMode) IsDir ¶
IsDir reports whether m describes a directory. That is, it tests for m.Type() == ModeDir.
func (FileMode) IsRegular ¶
IsRegular reports whether m describes a regular file. That is, it tests for m.Type() == ModeRegular
type FileStat ¶
type FileStat struct { Size uint64 Mode uint32 Mtime uint32 Atime uint32 UID uint32 GID uint32 Extended []StatExtended }
FileStat holds the original unmarshalled values from a call to READDIR or *STAT. It is exported for the purposes of accessing the raw values via os.FileInfo.Sys(). It is also used server side to store the unmarshalled values for SetStat.
func (*FileStat) AccessTime ¶
AccessTime returns the Atime SFTP file attribute converted to a time.Time
func (*FileStat) OsFileMode ¶
returns the Mode SFTP file attribute converted to an os.FileMode
type ReadDirFilter ¶
return allow=true to allow file, stop=true to stop making server reqs
type ReadDirLimit ¶
type ReadDirLimit struct {
N int
}
type StatExtended ¶
StatExtended contains additional, extended information for a FileStat.
type StatStrategy ¶
type StatStrategy uint8
Strategy for File.WriteTo, File.Read, File.ReadAt, File.Seek.
What to do when one of these is called and the actual file size must be known.
Files that were created from ReadDir have a cached set of attributes. Calling File.Stat also caches attributes (this includes calls caused by strategy).
const ( // Strategy for File.WriteTo, File.Read, File.ReadAt, File.Seek. // // Issue a stat call to the sftp server only if File's cached attributes are // not set. // // This is the default strategy. LazyStat StatStrategy = 0 // Strategy for File.WriteTo, File.Read, File.ReadAt, File.Seek. // // Never issue a stat call, even if the File has no cached attributes. // Instead error if size is needed but unknown. NeverStat StatStrategy = 1 // Strategy for File.WriteTo, File.Read, File.ReadAt, File.Seek. // // Always issue a Stat call to the sftp server to get the curent File size, // even if the size is already cached. AlwaysStat StatStrategy = 2 )
type StatVFS ¶
type StatVFS struct { ID uint32 Bsize uint64 // file system block size Frsize uint64 // fundamental fs block size Blocks uint64 // number of blocks (unit f_frsize) Bfree uint64 // free blocks in file system Bavail uint64 // free blocks for non-root Files uint64 // total file inodes Ffree uint64 // free file inodes Favail uint64 // free file inodes for to non-root Fsid uint64 // file system id Flag uint64 // bit mask of f_flag values Namemax uint64 // maximum filename length }
Statistics about a filesystem.
func (*StatVFS) TotalSpace ¶
TotalSpace calculates the amount of total space in a filesystem.
type StatusError ¶
type StatusError struct { Code uint32 // contains filtered or unexported fields }
A StatusError is returned when an SFTP operation fails, and provides additional information about the failure.
func (*StatusError) Error ¶
func (s *StatusError) Error() string
func (*StatusError) FxCode ¶
func (s *StatusError) FxCode() fxerr
FxCode returns the error code typed to match against the exported codes