123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380 |
- // Package ftp implements a FTP client as described in RFC 959.
- //
- // A textproto.Error is returned for errors at the protocol level.
- // This is a stripped down version of
- // github.com/jlaffaye/ftp@v0.0.0-20191218041957-e1b8fdd0dcc3
- package ftp
- import (
- "context"
- "errors"
- "io"
- "net"
- "net/textproto"
- "strconv"
- "strings"
- "time"
- )
- // EntryType describes the different types of an Entry.
- type EntryType int
- // The differents types of an Entry
- const (
- EntryTypeFile EntryType = iota
- EntryTypeFolder
- EntryTypeLink
- )
- // 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.
- type ServerConn struct {
- options *dialOptions
- conn *textproto.Conn
- host string
- // Server capabilities discovered at runtime
- features map[string]string
- mlstSupported bool
- }
- // DialOption represents an option to start a new connection with Dial
- type DialOption struct {
- setup func(do *dialOptions)
- }
- // dialOptions contains all the options set by DialOption.setup
- type dialOptions struct {
- context context.Context
- dialer net.Dialer
- conn net.Conn
- disableEPSV bool
- location *time.Location
- }
- // Response represents a data-connection
- type Response struct {
- conn net.Conn
- c *ServerConn
- closed bool
- }
- // Dial connects to the specified address with optional options
- func Dial(addr string, options ...DialOption) (*ServerConn, error) {
- do := &dialOptions{}
- for _, option := range options {
- option.setup(do)
- }
- if do.location == nil {
- do.location = time.UTC
- }
- tconn := do.conn
- if tconn == nil {
- var err error
- ctx := do.context
- if ctx == nil {
- ctx = context.Background()
- }
- tconn, err = do.dialer.DialContext(ctx, "tcp", addr)
- if err != nil {
- return nil, err
- }
- }
- // Use the resolved IP address in case addr contains a domain name
- // If we use the domain name, we might not resolve to the same IP.
- remoteAddr := tconn.RemoteAddr().(*net.TCPAddr)
- var sourceConn io.ReadWriteCloser = tconn
- // if do.debugOutput != nil {
- // sourceConn = newDebugWrapper(tconn, do.debugOutput)
- // }
- c := &ServerConn{
- options: do,
- features: make(map[string]string),
- conn: textproto.NewConn(sourceConn),
- host: remoteAddr.IP.String(),
- }
- _, _, err := c.conn.ReadResponse(StatusReady)
- if err != nil {
- c.Quit()
- return nil, err
- }
- err = c.feat()
- if err != nil {
- c.Quit()
- return nil, err
- }
- if _, mlstSupported := c.features["MLST"]; mlstSupported {
- c.mlstSupported = true
- }
- return c, nil
- }
- // DialWithTimeout returns a DialOption that configures the ServerConn with specified timeout
- func DialWithTimeout(timeout time.Duration) DialOption {
- return DialOption{func(do *dialOptions) {
- do.dialer.Timeout = timeout
- }}
- }
- // DialWithDisabledEPSV returns a DialOption that configures the ServerConn with EPSV disabled
- // Note that EPSV is only used when advertised in the server features.
- func DialWithDisabledEPSV(disabled bool) DialOption {
- return DialOption{func(do *dialOptions) {
- do.disableEPSV = disabled
- }}
- }
- // DialTimeout initializes the connection to the specified ftp server address.
- //
- // It is generally followed by a call to Login() as most FTP commands require
- // an authenticated user.
- func DialTimeout(addr string, timeout time.Duration) (*ServerConn, error) {
- return Dial(addr, DialWithTimeout(timeout))
- }
- // 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 (c *ServerConn) Login(user, password string) error {
- code, message, err := c.cmd(-1, "USER %s", user)
- if err != nil {
- return err
- }
- switch code {
- case StatusLoggedIn:
- case StatusUserOK:
- _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
- if err != nil {
- return err
- }
- default:
- return errors.New(message)
- }
- // Switch to binary mode
- if _, _, err = c.cmd(StatusCommandOK, "TYPE I"); err != nil {
- return err
- }
- return err
- }
- // feat issues a FEAT FTP command to list the additional commands supported by
- // the remote FTP server.
- // FEAT is described in RFC 2389
- func (c *ServerConn) feat() error {
- code, message, err := c.cmd(-1, "FEAT")
- if err != nil {
- return err
- }
- if code != StatusSystem {
- // The server does not support the FEAT command. This is not an
- // error: we consider that there is no additional feature.
- return nil
- }
- lines := strings.Split(message, "\n")
- for _, line := range lines {
- if !strings.HasPrefix(line, " ") {
- continue
- }
- line = strings.TrimSpace(line)
- featureElements := strings.SplitN(line, " ", 2)
- command := featureElements[0]
- var commandDesc string
- if len(featureElements) == 2 {
- commandDesc = featureElements[1]
- }
- c.features[command] = commandDesc
- }
- return nil
- }
- // pasv issues a "PASV" command to get a port number for a data connection.
- func (c *ServerConn) pasv() (host string, port int, err error) {
- _, line, err := c.cmd(StatusPassiveMode, "PASV")
- if err != nil {
- return
- }
- // PASV response format : 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
- start := strings.Index(line, "(")
- end := strings.LastIndex(line, ")")
- if start == -1 || end == -1 {
- err = errors.New("invalid PASV response format")
- return
- }
- // We have to split the response string
- pasvData := strings.Split(line[start+1:end], ",")
- if len(pasvData) < 6 {
- err = errors.New("invalid PASV response format")
- return
- }
- // Let's compute the port number
- portPart1, err1 := strconv.Atoi(pasvData[4])
- if err1 != nil {
- err = err1
- return
- }
- portPart2, err2 := strconv.Atoi(pasvData[5])
- if err2 != nil {
- err = err2
- return
- }
- // Recompose port
- port = portPart1*256 + portPart2
- // Make the IP address to connect to
- host = strings.Join(pasvData[0:4], ".")
- return
- }
- // getDataConnPort returns a host, port for a new data connection
- func (c *ServerConn) getDataConnPort() (string, int, error) {
- return c.pasv()
- }
- // openDataConn creates a new FTP data connection.
- func (c *ServerConn) openDataConn() (net.Conn, error) {
- host, port, err := c.getDataConnPort()
- if err != nil {
- return nil, err
- }
- addr := net.JoinHostPort(host, strconv.Itoa(port))
- return c.options.dialer.Dial("tcp", addr)
- }
- // cmd is a helper function to execute a command and check for the expected FTP
- // return code
- func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
- _, err := c.conn.Cmd(format, args...)
- if err != nil {
- return 0, "", err
- }
- return c.conn.ReadResponse(expected)
- }
- // cmdDataConnFrom executes a command which require a FTP data connection.
- // Issues a REST FTP command to specify the number of bytes to skip for the transfer.
- func (c *ServerConn) cmdDataConnFrom(offset uint64, format string, args ...interface{}) (net.Conn, error) {
- conn, err := c.openDataConn()
- if err != nil {
- return nil, err
- }
- if offset != 0 {
- _, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
- if err != nil {
- conn.Close()
- return nil, err
- }
- }
- _, err = c.conn.Cmd(format, args...)
- if err != nil {
- conn.Close()
- return nil, err
- }
- code, msg, err := c.conn.ReadResponse(-1)
- if err != nil {
- conn.Close()
- return nil, err
- }
- if code != StatusAlreadyOpen && code != StatusAboutToSend {
- conn.Close()
- return nil, &textproto.Error{Code: code, Msg: msg}
- }
- return conn, nil
- }
- // 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 (c *ServerConn) Retr(path string) (*Response, error) {
- return c.RetrFrom(path, 0)
- }
- // 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 (c *ServerConn) RetrFrom(path string, offset uint64) (*Response, error) {
- conn, err := c.cmdDataConnFrom(offset, "RETR %s", path)
- if err != nil {
- return nil, err
- }
- return &Response{conn: conn, c: c}, nil
- }
- // Logout issues a REIN FTP command to logout the current user.
- func (c *ServerConn) Logout() error {
- _, _, err := c.cmd(StatusReady, "REIN")
- return err
- }
- // Quit issues a QUIT FTP command to properly close the connection from the
- // remote FTP server.
- func (c *ServerConn) Quit() error {
- c.conn.Cmd("QUIT")
- return c.conn.Close()
- }
- // Read implements the io.Reader interface on a FTP data connection.
- func (r *Response) Read(buf []byte) (int, error) {
- return r.conn.Read(buf)
- }
- // Close implements the io.Closer interface on a FTP data connection.
- // After the first call, Close will do nothing and return nil.
- func (r *Response) Close() error {
- if r.closed {
- return nil
- }
- err := r.conn.Close()
- _, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)
- if err2 != nil {
- err = err2
- }
- r.closed = true
- return err
- }
- // SetDeadline sets the deadlines associated with the connection.
- func (r *Response) SetDeadline(t time.Time) error {
- return r.conn.SetDeadline(t)
- }
|