ftp

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 23, 2023 License: ISC Imports: 13 Imported by: 535

README

goftp

Units tests Coverage Status golangci-lint CodeQL Go ReportCard Go Reference

A FTP client package for Go

Install

go get -u github.com/jlaffaye/ftp

Documentation

https://pkg.go.dev/github.com/jlaffaye/ftp

Example

c, err := ftp.Dial("ftp.example.org:21", ftp.DialWithTimeout(5*time.Second))
if err != nil {
    log.Fatal(err)
}

err = c.Login("anonymous", "anonymous")
if err != nil {
    log.Fatal(err)
}

// Do something with the FTP conn

if err := c.Quit(); err != nil {
    log.Fatal(err)
}

Store a file example

data := bytes.NewBufferString("Hello World")
err = c.Stor("test-file.txt", data)
if err != nil {
	panic(err)
}

Read a file example

r, err := c.Retr("test-file.txt")
if err != nil {
	panic(err)
}
defer r.Close()

buf, err := ioutil.ReadAll(r)
println(string(buf))

Documentation

Overview

Package ftp implements a FTP client as described in RFC 959.

A textproto.Error is returned for errors at the protocol level.

Index

Constants

View Source
const (
	TransferTypeBinary = TransferType("I")
	TransferTypeASCII  = TransferType("A")
)

The different transfer types

View Source
const (
	StatusInitiating    = 100
	StatusRestartMarker = 110
	StatusReadyMinute   = 120
	StatusAlreadyOpen   = 125
	StatusAboutToSend   = 150

	StatusCommandOK             = 200
	StatusCommandNotImplemented = 202
	StatusSystem                = 211
	StatusDirectory             = 212
	StatusFile                  = 213
	StatusHelp                  = 214
	StatusName                  = 215
	StatusReady                 = 220
	StatusClosing               = 221
	StatusDataConnectionOpen    = 225
	StatusClosingDataConnection = 226
	StatusPassiveMode           = 227
	StatusLongPassiveMode       = 228
	StatusExtendedPassiveMode   = 229
	StatusLoggedIn              = 230
	StatusLoggedOut             = 231
	StatusLogoutAck             = 232
	StatusAuthOK                = 234
	StatusRequestedFileActionOK = 250
	StatusPathCreated           = 257

	StatusUserOK             = 331
	StatusLoginNeedAccount   = 332
	StatusRequestFilePending = 350

	StatusNotAvailable             = 421
	StatusCanNotOpenDataConnection = 425
	StatusTransfertAborted         = 426
	StatusInvalidCredentials       = 430
	StatusHostUnavailable          = 434
	StatusFileActionIgnored        = 450
	StatusActionAborted            = 451
	Status452                      = 452

	StatusBadCommand              = 500
	StatusBadArguments            = 501
	StatusNotImplemented          = 502
	StatusBadSequence             = 503
	StatusNotImplementedParameter = 504
	StatusNotLoggedIn             = 530
	StatusStorNeedAccount         = 532
	StatusFileUnavailable         = 550
	StatusPageTypeUnknown         = 551
	StatusExceededStorage         = 552
	StatusBadFileName             = 553
)

FTP status codes, defined in RFC 959

View Source
const (
	// 30 seconds was chosen as it's the
	// same duration as http.DefaultTransport's timeout.
	DefaultDialTimeout = 30 * time.Second
)

Variables

This section is empty.

Functions

func StatusText

func StatusText(code int) string

StatusText returns a text for the FTP status code. It returns the empty string if the code is unknown.

Types

type DialOption

type DialOption struct {
	// contains filtered or unexported fields
}

DialOption represents an option to start a new connection with Dial

func DialWithContext

func DialWithContext(ctx context.Context) DialOption

DialWithContext returns a DialOption that configures the ServerConn with specified context The context will be used for the initial connection setup

func DialWithDebugOutput

func DialWithDebugOutput(w io.Writer) DialOption

DialWithDebugOutput returns a DialOption that configures the ServerConn to write to the Writer everything it reads from the server

func DialWithDialFunc

func DialWithDialFunc(f func(network, address string) (net.Conn, error)) DialOption

DialWithDialFunc returns a DialOption that configures the ServerConn to use the specified function to establish both control and data connections

If used together with the DialWithNetConn option, the DialWithNetConn takes precedence for the control connection, while data connections will be established using function specified with the DialWithDialFunc option

func DialWithDialer

func DialWithDialer(dialer net.Dialer) DialOption

DialWithDialer returns a DialOption that configures the ServerConn with specified net.Dialer

func DialWithDisabledEPSV

func DialWithDisabledEPSV(disabled bool) DialOption

DialWithDisabledEPSV returns a DialOption that configures the ServerConn with EPSV disabled Note that EPSV is only used when advertised in the server features.

func DialWithDisabledMLSD

func DialWithDisabledMLSD(disabled bool) DialOption

DialWithDisabledMLSD returns a DialOption that configures the ServerConn with MLSD option disabled

This is useful for servers which advertise MLSD (eg some versions of Serv-U) but don't support it properly.

func DialWithDisabledUTF8

func DialWithDisabledUTF8(disabled bool) DialOption

DialWithDisabledUTF8 returns a DialOption that configures the ServerConn with UTF8 option disabled

func DialWithExplicitTLS

func DialWithExplicitTLS(tlsConfig *tls.Config) DialOption

DialWithExplicitTLS returns a DialOption that configures the ServerConn to be upgraded to TLS See DialWithTLS for general TLS documentation

func DialWithForceListHidden

func DialWithForceListHidden(enabled bool) DialOption

DialWithForceListHidden returns a DialOption making ServerConn use LIST -a to include hidden files and folders in directory listings

This is useful for servers that do not do this by default, but it forces the use of the LIST command even if the server supports MLST.

func DialWithLocation

func DialWithLocation(location *time.Location) DialOption

DialWithLocation returns a DialOption that configures the ServerConn with specified time.Location The location is used to parse the dates sent by the server which are in server's timezone

func DialWithNetConn deprecated

func DialWithNetConn(conn net.Conn) DialOption

DialWithNetConn returns a DialOption that configures the ServerConn with the underlying net.Conn

Deprecated: Use DialWithDialFunc instead

func DialWithShutTimeout

func DialWithShutTimeout(shutTimeout time.Duration) DialOption

DialWithShutTimeout returns a DialOption that configures the ServerConn with maximum time to wait for the data closing status on control connection and nudging the control connection deadline before reading status.

func DialWithTLS

func DialWithTLS(tlsConfig *tls.Config) DialOption

DialWithTLS returns a DialOption that configures the ServerConn with specified TLS config

If called together with the DialWithDialFunc option, the DialWithDialFunc function will be used when dialing new connections but regardless of the function, the connection will be treated as a TLS connection.

func DialWithTimeout

func DialWithTimeout(timeout time.Duration) DialOption

DialWithTimeout returns a DialOption that configures the ServerConn with specified timeout

func DialWithWritingMDTM

func DialWithWritingMDTM(enabled bool) DialOption

DialWithWritingMDTM returns a DialOption making ServerConn use MDTM to set file time

This option addresses a quirk in the VsFtpd server which doesn't support the MFMT command for setting file time like other servers but by default uses the MDTM command with non-standard arguments for that. See "mdtm_write" in https://security.appspot.com/vsftpd/vsftpd_conf.html

type Entry

type Entry struct {
	Name   string
	Target string // target of symbolic link
	Type   EntryType
	Size   uint64
	Time   time.Time
}

Entry describes a file and is returned by List().

type EntryType

type EntryType int

EntryType describes the different types of an Entry.

const (
	EntryTypeFile EntryType = iota
	EntryTypeFolder
	EntryTypeLink
)

The differents types of an Entry

func (EntryType) String

func (t EntryType) String() string

String returns the string representation of EntryType t.

type Response

type Response struct {
	// contains filtered or unexported fields
}

Response represents a data-connection

func (*Response) Close

func (r *Response) Close() error

Close implements the io.Closer interface on a FTP data connection. After the first call, Close will do nothing and return nil.

func (*Response) Read

func (r *Response) Read(buf []byte) (int, error)

Read implements the io.Reader interface on a FTP data connection.

func (*Response) SetDeadline

func (r *Response) SetDeadline(t time.Time) error

SetDeadline sets the deadlines associated with the connection.

type ServerConn

type ServerConn struct {
	// contains filtered or unexported fields
}

ServerConn represents the connection to a remote FTP server. A single connection only supports one in-flight data connection. It is not safe to be called concurrently.

func Connect deprecated

func Connect(addr string) (*ServerConn, error)

Connect is an alias to Dial, for backward compatibility

Deprecated: Use Dial instead

func Dial

func Dial(addr string, options ...DialOption) (*ServerConn, error)

Dial connects to the specified address with optional options

func DialTimeout deprecated

func DialTimeout(addr string, timeout time.Duration) (*ServerConn, error)

DialTimeout initializes the connection to the specified ftp server address.

Deprecated: Use Dial with DialWithTimeout option instead

func (*ServerConn) Append

func (c *ServerConn) Append(path string, r io.Reader) error

Append issues a APPE FTP command to store a file to the remote FTP server. If a file already exists with the given path, then the content of the io.Reader is appended. Otherwise, a new file is created with that content.

Hint: io.Pipe() can be used if an io.Writer is required.

func (*ServerConn) ChangeDir

func (c *ServerConn) ChangeDir(path string) error

ChangeDir issues a CWD FTP command, which changes the current directory to the specified path.

func (*ServerConn) ChangeDirToParent

func (c *ServerConn) ChangeDirToParent() error

ChangeDirToParent issues a CDUP FTP command, which changes the current directory to the parent directory. This is similar to a call to ChangeDir with a path set to "..".

func (*ServerConn) CurrentDir

func (c *ServerConn) CurrentDir() (string, error)

CurrentDir issues a PWD FTP command, which Returns the path of the current directory.

func (*ServerConn) Delete

func (c *ServerConn) Delete(path string) error

Delete issues a DELE FTP command to delete the specified file from the remote FTP server.

func (*ServerConn) FileSize

func (c *ServerConn) FileSize(path string) (int64, error)

FileSize issues a SIZE FTP command, which Returns the size of the file

func (*ServerConn) GetEntry

func (c *ServerConn) GetEntry(path string) (entry *Entry, err error)

GetEntry issues a MLST FTP command which retrieves one single Entry using the control connection. The returnedEntry will describe the current directory when no path is given.

func (*ServerConn) GetTime

func (c *ServerConn) GetTime(path string) (time.Time, error)

GetTime issues the MDTM FTP command to obtain the file modification time. It returns a UTC time.

func (*ServerConn) IsGetTimeSupported

func (c *ServerConn) IsGetTimeSupported() bool

IsGetTimeSupported allows library callers to check in advance that they can use GetTime to get file time.

func (*ServerConn) IsSetTimeSupported

func (c *ServerConn) IsSetTimeSupported() bool

IsSetTimeSupported allows library callers to check in advance that they can use SetTime to set file time.

func (*ServerConn) IsTimePreciseInList

func (c *ServerConn) IsTimePreciseInList() bool

IsTimePreciseInList returns true if client and server support the MLSD command so List can return time with 1-second precision for all files.

func (*ServerConn) List

func (c *ServerConn) List(path string) (entries []*Entry, err error)

List issues a LIST FTP command.

func (*ServerConn) Login

func (c *ServerConn) Login(user, password string) error

Login authenticates the client with specified user and password.

"anonymous"/"anonymous" is a common user/password scheme for FTP servers that allows anonymous read-only accounts.

func (*ServerConn) Logout

func (c *ServerConn) Logout() error

Logout issues a REIN FTP command to logout the current user.

func (*ServerConn) MakeDir

func (c *ServerConn) MakeDir(path string) error

MakeDir issues a MKD FTP command to create the specified directory on the remote FTP server.

func (*ServerConn) NameList

func (c *ServerConn) NameList(path string) (entries []string, err error)

NameList issues an NLST FTP command.

func (*ServerConn) NoOp

func (c *ServerConn) NoOp() error

NoOp issues a NOOP FTP command. NOOP has no effects and is usually used to prevent the remote FTP server to close the otherwise idle connection.

func (*ServerConn) Quit

func (c *ServerConn) Quit() error

Quit issues a QUIT FTP command to properly close the connection from the remote FTP server.

func (*ServerConn) RemoveDir

func (c *ServerConn) RemoveDir(path string) error

RemoveDir issues a RMD FTP command to remove the specified directory from the remote FTP server.

func (*ServerConn) RemoveDirRecur

func (c *ServerConn) RemoveDirRecur(path string) error

RemoveDirRecur deletes a non-empty folder recursively using RemoveDir and Delete

func (*ServerConn) Rename

func (c *ServerConn) Rename(from, to string) error

Rename renames a file on the remote FTP server.

func (*ServerConn) Retr

func (c *ServerConn) Retr(path string) (*Response, error)

Retr issues a RETR FTP command to fetch the specified file from the remote FTP server.

The returned ReadCloser must be closed to cleanup the FTP data connection.

func (*ServerConn) RetrFrom

func (c *ServerConn) RetrFrom(path string, offset uint64) (*Response, error)

RetrFrom issues a RETR FTP command to fetch the specified file from the remote FTP server, the server will not send the offset first bytes of the file.

The returned ReadCloser must be closed to cleanup the FTP data connection.

func (*ServerConn) SetTime

func (c *ServerConn) SetTime(path string, t time.Time) (err error)

SetTime issues the MFMT FTP command to set the file modification time. Also it can use a non-standard form of the MDTM command supported by the VsFtpd server instead of MFMT for the same purpose. See "mdtm_write" in https://security.appspot.com/vsftpd/vsftpd_conf.html

func (*ServerConn) Stor

func (c *ServerConn) Stor(path string, r io.Reader) error

Stor issues a STOR FTP command to store a file to the remote FTP server. Stor creates the specified file with the content of the io.Reader.

Hint: io.Pipe() can be used if an io.Writer is required.

func (*ServerConn) StorFrom

func (c *ServerConn) StorFrom(path string, r io.Reader, offset uint64) error

StorFrom issues a STOR FTP command to store a file to the remote FTP server. Stor creates the specified file with the content of the io.Reader, writing on the server will start at the given file offset.

Hint: io.Pipe() can be used if an io.Writer is required.

func (*ServerConn) Type

func (c *ServerConn) Type(transferType TransferType) (err error)

Type switches the transfer mode for the connection.

func (*ServerConn) Walk

func (c *ServerConn) Walk(root string) *Walker

Walk prepares the internal walk function so that the caller can begin traversing the directory

type TransferType

type TransferType string

TransferType denotes the formats for transferring Entries.

type Walker

type Walker struct {
	// contains filtered or unexported fields
}

Walker traverses the directory tree of a remote FTP server

func (*Walker) Err

func (w *Walker) Err() error

Err returns the error, if any, for the most recent attempt by Next to visit a file or a directory. If a directory has an error, the walker will not descend in that directory

func (*Walker) Next

func (w *Walker) Next() bool

Next advances the Walker to the next file or directory, which will then be available through the Path, Stat, and Err methods. It returns false when the walk stops at the end of the tree.

func (*Walker) Path

func (w *Walker) Path() string

Path returns the path to the most recent file or directory visited by a call to Next. It contains the argument to Walk as a prefix; that is, if Walk is called with "dir", which is a directory containing the file "a", Path will return "dir/a".

func (*Walker) SkipDir

func (w *Walker) SkipDir()

SkipDir tells the Next function to skip the currently processed directory

func (*Walker) Stat

func (w *Walker) Stat() *Entry

Stat returns info for the most recent file or directory visited by a call to Next.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL