ftp/ftp.go

882 lines
23 KiB
Go
Raw Normal View History

2013-05-19 13:09:37 +02:00
// Package ftp implements a FTP client as described in RFC 959.
//
// A textproto.Error is returned for errors at the protocol level.
2011-05-07 01:29:10 +02:00
package ftp
import (
"bufio"
"context"
"crypto/tls"
2013-02-17 10:03:46 +01:00
"errors"
"io"
2011-05-07 01:29:10 +02:00
"net"
2011-05-07 13:56:42 +02:00
"net/textproto"
2011-05-07 01:29:10 +02:00
"strconv"
"strings"
2013-07-08 07:21:43 +02:00
"time"
2011-05-07 01:29:10 +02:00
)
2013-05-19 13:09:37 +02:00
// EntryType describes the different types of an Entry.
type EntryType int
2015-03-05 11:57:38 +01:00
// The differents types of an Entry
2011-05-07 01:29:10 +02:00
const (
EntryTypeFile EntryType = iota
2011-05-07 01:29:10 +02:00
EntryTypeFolder
EntryTypeLink
)
2013-05-19 13:09:37 +02:00
// 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
2017-02-05 21:02:16 +01:00
// Server capabilities discovered at runtime
2017-01-01 16:41:42 +01:00
features map[string]string
skipEPSV bool
2017-01-01 16:41:42 +01:00
mlstSupported bool
usePRET bool
2011-05-07 01:29:10 +02:00
}
// 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
tlsConfig *tls.Config
2020-04-23 00:49:43 +02:00
explicitTLS bool
conn net.Conn
disableEPSV bool
2020-07-28 21:13:33 +02:00
disableUTF8 bool
disableMLSD bool
location *time.Location
debugOutput io.Writer
dialFunc func(network, address string) (net.Conn, error)
}
2013-05-19 13:09:37 +02:00
// Entry describes a file and is returned by List().
2011-05-07 01:29:10 +02:00
type Entry struct {
Name string
Target string // target of symbolic link
Type EntryType
Size uint64
Time time.Time
2011-05-07 01:29:10 +02:00
}
2017-04-15 11:53:19 +02:00
// Response represents a data-connection
type Response struct {
2017-05-05 02:46:29 +02:00
conn net.Conn
c *ServerConn
closed bool
}
2019-07-21 21:44:32 +02:00
// 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
if do.dialFunc != nil {
tconn, err = do.dialFunc("tcp", addr)
2020-04-23 00:49:43 +02:00
} else if do.tlsConfig != nil && !do.explicitTLS {
2019-07-21 21:36:15 +02:00
tconn, err = tls.DialWithDialer(&do.dialer, "tcp", addr, do.tlsConfig)
} else {
ctx := do.context
if ctx == nil {
ctx = context.Background()
}
tconn, err = do.dialer.DialContext(ctx, "tcp", addr)
}
if err != nil {
return nil, err
}
2011-05-07 01:29:10 +02:00
}
// 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)
c := &ServerConn{
options: do,
features: make(map[string]string),
2020-04-23 00:49:43 +02:00
conn: textproto.NewConn(do.wrapConn(tconn)),
host: remoteAddr.IP.String(),
}
2011-05-07 01:29:10 +02:00
_, _, err := c.conn.ReadResponse(StatusReady)
2011-05-07 01:29:10 +02:00
if err != nil {
c.Quit()
2011-05-07 01:29:10 +02:00
return nil, err
}
2020-04-23 00:49:43 +02:00
if do.explicitTLS {
if err := c.authTLS(); err != nil {
_ = c.Quit()
return nil, err
}
tconn = tls.Client(tconn, do.tlsConfig)
c.conn = textproto.NewConn(do.wrapConn(tconn))
}
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
}}
}
// DialWithDialer returns a DialOption that configures the ServerConn with specified net.Dialer
func DialWithDialer(dialer net.Dialer) DialOption {
return DialOption{func(do *dialOptions) {
do.dialer = dialer
}}
}
// DialWithNetConn returns a DialOption that configures the ServerConn with the underlying net.Conn
func DialWithNetConn(conn net.Conn) DialOption {
return DialOption{func(do *dialOptions) {
do.conn = conn
}}
}
// 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
}}
}
2020-07-28 21:13:33 +02:00
// DialWithDisabledUTF8 returns a DialOption that configures the ServerConn with UTF8 option disabled
func DialWithDisabledUTF8(disabled bool) DialOption {
return DialOption{func(do *dialOptions) {
do.disableUTF8 = disabled
}}
}
// 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 DialWithDisabledMLSD(disabled bool) DialOption {
return DialOption{func(do *dialOptions) {
do.disableMLSD = disabled
}}
}
// DialWithLocation returns a DialOption that configures the ServerConn with specified time.Location
2019-07-21 21:44:32 +02:00
// The location is used to parse the dates sent by the server which are in server's timezone
func DialWithLocation(location *time.Location) DialOption {
return DialOption{func(do *dialOptions) {
do.location = location
}}
}
// DialWithContext returns a DialOption that configures the ServerConn with specified context
// The context will be used for the initial connection setup
func DialWithContext(ctx context.Context) DialOption {
return DialOption{func(do *dialOptions) {
do.context = ctx
}}
}
// DialWithTLS returns a DialOption that configures the ServerConn with specified TLS config
2019-07-21 21:36:15 +02:00
//
// 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 DialWithTLS(tlsConfig *tls.Config) DialOption {
return DialOption{func(do *dialOptions) {
do.tlsConfig = tlsConfig
}}
}
2020-04-23 00:49:43 +02:00
// DialWithExplicitTLS returns a DialOption that configures the ServerConn to be upgraded to TLS
// See DialWithTLS for general TLS documentation
func DialWithExplicitTLS(tlsConfig *tls.Config) DialOption {
return DialOption{func(do *dialOptions) {
do.explicitTLS = true
do.tlsConfig = tlsConfig
}}
}
// DialWithDebugOutput returns a DialOption that configures the ServerConn to write to the Writer
// everything it reads from the server
func DialWithDebugOutput(w io.Writer) DialOption {
return DialOption{func(do *dialOptions) {
do.debugOutput = w
}}
}
// 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 DialWithDialFunc(f func(network, address string) (net.Conn, error)) DialOption {
return DialOption{func(do *dialOptions) {
do.dialFunc = f
}}
}
2020-04-23 00:49:43 +02:00
func (o *dialOptions) wrapConn(netConn net.Conn) io.ReadWriteCloser {
if o.debugOutput == nil {
return netConn
}
return newDebugWrapper(netConn, o.debugOutput)
}
// Connect is an alias to Dial, for backward compatibility
func Connect(addr string) (*ServerConn, error) {
return Dial(addr)
}
// 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))
}
2013-05-19 13:09:37 +02:00
// 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.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) Login(user, password string) error {
code, message, err := c.cmd(-1, "USER %s", user)
2011-05-07 01:29:10 +02:00
if err != nil {
return err
2011-05-07 01:29:10 +02:00
}
switch code {
case StatusLoggedIn:
case StatusUserOK:
_, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
if err != nil {
return err
}
default:
return errors.New(message)
}
// Probe features
err = c.feat()
if err != nil {
return err
}
if _, mlstSupported := c.features["MLST"]; mlstSupported && !c.options.disableMLSD {
c.mlstSupported = true
}
if _, usePRET := c.features["PRET"]; usePRET {
c.usePRET = true
}
// Switch to binary mode
2017-02-04 12:24:16 +01:00
if _, _, err = c.cmd(StatusCommandOK, "TYPE I"); err != nil {
return err
}
// Switch to UTF-8
2020-07-28 21:13:33 +02:00
if !c.options.disableUTF8 {
err = c.setUTF8()
}
// If using implicit TLS, make data connections also use TLS
if c.options.tlsConfig != nil {
c.cmd(StatusCommandOK, "PBSZ 0")
c.cmd(StatusCommandOK, "PROT P")
}
2018-01-04 15:23:55 +01:00
return err
2011-05-07 01:29:10 +02:00
}
2020-04-23 00:49:43 +02:00
// authTLS upgrades the connection to use TLS
func (c *ServerConn) authTLS() error {
_, _, err := c.cmd(StatusAuthOK, "AUTH TLS")
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
2013-05-20 01:20:29 +02:00
// 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
}
2017-01-09 04:45:58 +01:00
// setUTF8 issues an "OPTS UTF8 ON" command.
func (c *ServerConn) setUTF8() error {
if _, ok := c.features["UTF8"]; !ok {
return nil
}
code, message, err := c.cmd(-1, "OPTS UTF8 ON")
if err != nil {
return err
}
// Workaround for FTP servers, that does not support this option.
if code == StatusBadArguments || code == StatusNotImplementedParameter {
return nil
}
// The ftpd "filezilla-server" has FEAT support for UTF8, but always returns
// "202 UTF8 mode is always enabled. No need to send this command." when
// trying to use it. That's OK
if code == StatusCommandNotImplemented {
return nil
}
2017-01-09 04:45:58 +01:00
if code != StatusCommandOK {
return errors.New(message)
}
return nil
}
2013-05-19 13:09:37 +02:00
// epsv issues an "EPSV" command to get a port number for a data connection.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) epsv() (port int, err error) {
_, line, err := c.cmd(StatusExtendedPassiveMode, "EPSV")
2011-05-07 01:29:10 +02:00
if err != nil {
2020-10-20 19:13:30 +02:00
return 0, err
2011-05-07 01:29:10 +02:00
}
2011-05-07 01:29:10 +02:00
start := strings.Index(line, "|||")
end := strings.LastIndex(line, "|")
if start == -1 || end == -1 {
2020-10-20 19:13:30 +02:00
return 0, errors.New("invalid EPSV response format")
2011-05-07 01:29:10 +02:00
}
port, err = strconv.Atoi(line[start+3 : end])
2020-10-20 19:13:30 +02:00
return port, err
2011-05-07 01:29:10 +02:00
}
2013-09-07 18:48:40 +02:00
// pasv issues a "PASV" command to get a port number for a data connection.
func (c *ServerConn) pasv() (host string, port int, err error) {
2013-09-07 18:48:40 +02:00
_, line, err := c.cmd(StatusPassiveMode, "PASV")
if err != nil {
2020-10-20 19:13:30 +02:00
return "", 0, err
2013-09-07 18:48:40 +02:00
}
// 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 {
2020-10-20 19:13:30 +02:00
return "", 0, errors.New("invalid PASV response format")
2013-09-07 18:48:40 +02:00
}
// We have to split the response string
pasvData := strings.Split(line[start+1:end], ",")
if len(pasvData) < 6 {
2020-10-20 19:13:30 +02:00
return "", 0, errors.New("invalid PASV response format")
}
2013-09-07 18:48:40 +02:00
// Let's compute the port number
2020-10-20 19:13:30 +02:00
portPart1, err := strconv.Atoi(pasvData[4])
if err != nil {
return "", 0, err
2013-09-07 18:48:40 +02:00
}
2020-10-20 19:13:30 +02:00
portPart2, err := strconv.Atoi(pasvData[5])
if err != nil {
return "", 0, err
2013-09-07 18:48:40 +02:00
}
// Recompose port
port = portPart1*256 + portPart2
// Make the IP address to connect to
host = strings.Join(pasvData[0:4], ".")
2020-10-20 19:13:30 +02:00
return host, port, nil
2013-09-04 14:54:57 +02:00
}
// getDataConnPort returns a host, port for a new data connection
// it uses the best available method to do so
func (c *ServerConn) getDataConnPort() (string, int, error) {
if !c.options.disableEPSV && !c.skipEPSV {
if port, err := c.epsv(); err == nil {
return c.host, port, nil
}
// if there is an error, skip EPSV for the next attempts
c.skipEPSV = true
}
return c.pasv()
}
2013-05-19 13:09:37 +02:00
// openDataConn creates a new FTP data connection.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) openDataConn() (net.Conn, error) {
host, port, err := c.getDataConnPort()
if err != nil {
return nil, err
2011-05-07 01:29:10 +02:00
}
addr := net.JoinHostPort(host, strconv.Itoa(port))
if c.options.dialFunc != nil {
return c.options.dialFunc("tcp", addr)
}
if c.options.tlsConfig != nil {
conn, err := c.options.dialer.Dial("tcp", addr)
if err != nil {
return nil, err
}
return tls.Client(conn, c.options.tlsConfig), err
}
return c.options.dialer.Dial("tcp", addr)
}
2013-05-19 13:09:37 +02:00
// cmd is a helper function to execute a command and check for the expected FTP
// return code
2011-12-27 22:50:50 +01:00
func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
2011-09-06 19:12:22 +02:00
_, err := c.conn.Cmd(format, args...)
if err != nil {
return 0, "", err
}
2015-08-18 23:16:40 +02:00
return c.conn.ReadResponse(expected)
2011-09-06 19:12:22 +02:00
}
// 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) {
// If server requires PRET send the PRET command to warm it up
// See: https://tools.ietf.org/html/draft-dd-pret-00
if c.usePRET {
_, _, err := c.cmd(-1, "PRET "+format, args...)
if err != nil {
return nil, err
}
}
2011-09-06 19:12:22 +02:00
conn, err := c.openDataConn()
if err != nil {
return nil, err
}
if offset != 0 {
_, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
if err != nil {
2016-11-18 01:20:19 +01:00
conn.Close()
return nil, err
}
}
2011-09-06 19:12:22 +02:00
_, err = c.conn.Cmd(format, args...)
if err != nil {
conn.Close()
return nil, err
}
code, msg, err := c.conn.ReadResponse(-1)
if err != nil {
2011-09-06 19:12:22 +02:00
conn.Close()
return nil, err
}
if code != StatusAlreadyOpen && code != StatusAboutToSend {
2011-09-06 19:12:22 +02:00
conn.Close()
return nil, &textproto.Error{Code: code, Msg: msg}
}
2011-09-06 19:12:22 +02:00
return conn, nil
2011-05-07 01:29:10 +02:00
}
2013-12-04 01:09:55 +01:00
// NameList issues an NLST FTP command.
func (c *ServerConn) NameList(path string) (entries []string, err error) {
space := " "
if path == "" {
space = ""
}
conn, err := c.cmdDataConnFrom(0, "NLST%s%s", space, path)
2013-12-04 01:09:55 +01:00
if err != nil {
2020-10-20 19:13:30 +02:00
return nil, err
2013-12-04 01:09:55 +01:00
}
2017-05-04 22:03:00 +02:00
r := &Response{conn: conn, c: c}
2013-12-04 01:09:55 +01:00
defer r.Close()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
entries = append(entries, scanner.Text())
}
if err = scanner.Err(); err != nil {
return entries, err
}
2020-10-20 19:13:30 +02:00
return entries, nil
2013-12-04 01:09:55 +01:00
}
2013-05-19 13:09:37 +02:00
// List issues a LIST FTP command.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) List(path string) (entries []*Entry, err error) {
2017-01-01 16:41:42 +01:00
var cmd string
var parser parseFunc
2017-01-01 16:41:42 +01:00
if c.mlstSupported {
cmd = "MLSD"
parser = parseRFC3659ListLine
2017-01-01 16:41:42 +01:00
} else {
cmd = "LIST"
parser = parseListLine
2017-01-01 16:41:42 +01:00
}
space := " "
if path == "" {
space = ""
}
conn, err := c.cmdDataConnFrom(0, "%s%s%s", cmd, space, path)
2011-05-07 01:29:10 +02:00
if err != nil {
2020-10-20 19:13:30 +02:00
return nil, err
2011-05-07 01:29:10 +02:00
}
2017-05-04 22:03:00 +02:00
r := &Response{conn: conn, c: c}
2011-05-07 01:29:10 +02:00
defer r.Close()
scanner := bufio.NewScanner(r)
now := time.Now()
for scanner.Scan() {
entry, err := parser(scanner.Text(), now, c.options.location)
2011-05-07 01:29:10 +02:00
if err == nil {
entries = append(entries, entry)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
2020-10-20 19:13:30 +02:00
return entries, nil
2011-05-07 01:29:10 +02:00
}
2013-05-19 13:09:37 +02:00
// ChangeDir issues a CWD FTP command, which changes the current directory to
// the specified path.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) ChangeDir(path string) error {
2011-09-06 19:12:22 +02:00
_, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
return err
2011-05-07 01:29:10 +02:00
}
2013-05-19 13:09:37 +02:00
// 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 "..".
2011-12-27 22:50:50 +01:00
func (c *ServerConn) ChangeDirToParent() error {
_, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
return err
}
2013-05-19 13:09:37 +02:00
// CurrentDir issues a PWD FTP command, which Returns the path of the current
// directory.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) CurrentDir() (string, error) {
_, msg, err := c.cmd(StatusPathCreated, "PWD")
if err != nil {
return "", err
}
start := strings.Index(msg, "\"")
end := strings.LastIndex(msg, "\"")
if start == -1 || end == -1 {
return "", errors.New("unsuported PWD response format")
}
2011-12-27 22:50:50 +01:00
return msg[start+1 : end], nil
}
2017-02-19 14:44:20 +01:00
// FileSize issues a SIZE FTP command, which Returns the size of the file
func (c *ServerConn) FileSize(path string) (int64, error) {
2017-02-19 14:44:20 +01:00
_, msg, err := c.cmd(StatusFile, "SIZE %s", path)
if err != nil {
return 0, err
}
2017-02-20 06:34:20 +01:00
return strconv.ParseInt(msg, 10, 64)
2017-02-19 14:44:20 +01:00
}
2013-05-19 13:09:37 +02:00
// 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.
2017-04-15 11:53:19 +02:00
func (c *ServerConn) Retr(path string) (*Response, error) {
return c.RetrFrom(path, 0)
}
2015-11-30 12:22:16 +01:00
// 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.
2017-04-15 11:53:19 +02:00
func (c *ServerConn) RetrFrom(path string, offset uint64) (*Response, error) {
conn, err := c.cmdDataConnFrom(offset, "RETR %s", path)
if err != nil {
return nil, err
}
2017-05-04 22:03:00 +02:00
return &Response{conn: conn, c: c}, nil
}
2013-05-19 13:09:37 +02:00
// 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.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) Stor(path string, r io.Reader) error {
return c.StorFrom(path, r, 0)
}
2015-11-30 12:22:16 +01:00
// 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 (c *ServerConn) StorFrom(path string, r io.Reader, offset uint64) error {
conn, err := c.cmdDataConnFrom(offset, "STOR %s", path)
if err != nil {
return err
}
// if the upload fails we still need to try to read the server
// response otherwise if the failure is not due to a connection problem,
// for example the server denied the upload for quota limits, we miss
// the response and we cannot use the connection to send other commands.
// So we don't check io.Copy error and we return the error from
// ReadResponse so the user can see the real error
var n int64
n, err = io.Copy(conn, r)
// If we wrote no bytes but got no error, make sure we call
// tls.Handshake on the connection as it won't get called
// unless Write() is called.
//
// ProFTP doesn't like this and returns "Unable to build data
// connection: Operation not permitted" when trying to upload
// an empty file without this.
if n == 0 && err == nil {
if do, ok := conn.(interface{ Handshake() error }); ok {
err = do.Handshake()
}
}
// Use io.Copy or Handshake error in preference to this one
closeErr := conn.Close()
if err == nil {
err = closeErr
}
// Read the response and use this error in preference to
// previous errors
_, _, respErr := c.conn.ReadResponse(StatusClosingDataConnection)
if respErr != nil {
err = respErr
}
return err
}
2020-03-10 11:43:17 +01:00
// 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 (c *ServerConn) Append(path string, r io.Reader) error {
conn, err := c.cmdDataConnFrom(0, "APPE %s", path)
if err != nil {
return err
}
// see the comment for StorFrom above
_, err = io.Copy(conn, r)
2020-03-10 11:43:17 +01:00
conn.Close()
_, _, respErr := c.conn.ReadResponse(StatusClosingDataConnection)
if respErr != nil {
err = respErr
}
return err
}
2013-05-19 13:09:37 +02:00
// Rename renames a file on the remote FTP server.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) Rename(from, to string) error {
2011-09-06 19:12:22 +02:00
_, _, err := c.cmd(StatusRequestFilePending, "RNFR %s", from)
if err != nil {
return err
}
2011-09-06 19:12:22 +02:00
_, _, err = c.cmd(StatusRequestedFileActionOK, "RNTO %s", to)
return err
}
2013-05-19 13:09:37 +02:00
// Delete issues a DELE FTP command to delete the specified file from the
// remote FTP server.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) Delete(path string) error {
_, _, err := c.cmd(StatusRequestedFileActionOK, "DELE %s", path)
return err
}
// RemoveDirRecur deletes a non-empty folder recursively using
// RemoveDir and Delete
func (c *ServerConn) RemoveDirRecur(path string) error {
err := c.ChangeDir(path)
if err != nil {
return err
}
currentDir, err := c.CurrentDir()
if err != nil {
return err
}
entries, err := c.List(currentDir)
if err != nil {
return err
}
for _, entry := range entries {
if entry.Name != ".." && entry.Name != "." {
if entry.Type == EntryTypeFolder {
err = c.RemoveDirRecur(currentDir + "/" + entry.Name)
if err != nil {
return err
}
} else {
err = c.Delete(entry.Name)
if err != nil {
return err
}
}
}
}
err = c.ChangeDirToParent()
if err != nil {
return err
}
err = c.RemoveDir(currentDir)
return err
}
2013-05-19 13:09:37 +02:00
// MakeDir issues a MKD FTP command to create the specified directory on the
// remote FTP server.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) MakeDir(path string) error {
_, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
return err
}
2013-05-19 13:09:37 +02:00
// RemoveDir issues a RMD FTP command to remove the specified directory from
// the remote FTP server.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) RemoveDir(path string) error {
_, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", path)
return err
}
//Walk prepares the internal walk function so that the caller can begin traversing the directory
func (c *ServerConn) Walk(root string) *Walker {
w := new(Walker)
w.serverConn = c
if !strings.HasSuffix(root, "/") {
root += "/"
}
w.root = root
2020-04-25 18:27:59 +02:00
w.descend = true
return w
}
2013-05-19 13:09:37 +02:00
// 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.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) NoOp() error {
2011-09-06 19:12:22 +02:00
_, _, err := c.cmd(StatusCommandOK, "NOOP")
return err
2011-05-07 01:29:10 +02:00
}
2013-05-19 21:15:23 +02:00
// Logout issues a REIN FTP command to logout the current user.
func (c *ServerConn) Logout() error {
_, _, err := c.cmd(StatusReady, "REIN")
2013-05-19 21:15:23 +02:00
return err
}
2013-05-19 13:09:37 +02:00
// Quit issues a QUIT FTP command to properly close the connection from the
// remote FTP server.
2011-12-27 22:50:50 +01:00
func (c *ServerConn) Quit() error {
2011-05-07 13:56:42 +02:00
c.conn.Cmd("QUIT")
return c.conn.Close()
2011-05-07 01:29:10 +02:00
}
2013-05-19 13:09:37 +02:00
// Read implements the io.Reader interface on a FTP data connection.
2017-04-15 11:53:19 +02:00
func (r *Response) Read(buf []byte) (int, error) {
2015-08-18 23:16:40 +02:00
return r.conn.Read(buf)
2011-05-07 01:29:10 +02:00
}
2013-05-19 13:09:37 +02:00
// Close implements the io.Closer interface on a FTP data connection.
// After the first call, Close will do nothing and return nil.
2017-04-15 11:53:19 +02:00
func (r *Response) Close() error {
2017-05-05 02:46:29 +02:00
if r.closed {
return nil
}
err := r.conn.Close()
2014-02-18 16:51:07 +01:00
_, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)
if err2 != nil {
err = err2
}
2017-05-05 02:46:29 +02:00
r.closed = true
return err
2011-05-07 01:29:10 +02:00
}
2017-04-15 11:53:19 +02:00
// SetDeadline sets the deadlines associated with the connection.
func (r *Response) SetDeadline(t time.Time) error {
return r.conn.SetDeadline(t)
}
2020-07-17 18:01:41 +02:00
// String returns the string representation of EntryType t.
func (t EntryType) String() string {
return [...]string{"file", "folder", "link"}[t]
}