rclone/ftp/ftp.go

442 lines
9.5 KiB
Go
Raw Normal View History

2016-12-27 20:52:30 +00:00
// Package fs is a generic file system interface for rclone object storage systems
package ftp
import (
"fmt"
"io"
"path/filepath"
"regexp"
"strconv"
"strings"
2017-05-03 12:18:17 +00:00
"sync"
"time"
"github.com/jlaffaye/ftp"
"github.com/ncw/rclone/fs"
2016-12-27 20:52:30 +00:00
)
// Register with Fs
func init() {
fs.Register(&fs.RegInfo{
2017-05-03 12:18:17 +00:00
Name: "Ftp",
2016-12-27 20:52:30 +00:00
Description: "FTP interface",
2017-05-03 12:18:17 +00:00
NewFs: NewFs,
2016-12-27 20:52:30 +00:00
Options: []fs.Option{
{
Name: "username",
Help: "Username",
}, {
Name: "password",
Help: "Password",
}, {
Name: "url",
Help: "FTP url",
},
},
})
}
type Url struct {
Scheme string
2017-05-03 12:18:17 +00:00
Host string
Port int
Path string
2016-12-27 20:52:30 +00:00
}
type Fs struct {
2017-05-03 12:18:17 +00:00
name string // name of this remote
root string // the path we are working on if any
features *fs.Features // optional features
c *ftp.ServerConn // the connection to the FTP server
url Url
mu sync.Mutex
2016-12-27 20:52:30 +00:00
}
type Object struct {
2017-05-03 12:18:17 +00:00
fs *Fs
remote string
info *FileInfo
2016-12-27 20:52:30 +00:00
}
type FileInfo struct {
Name string
Size uint64
ModTime time.Time
IsDir bool
}
// Implements ReadCloser for FTP objects.
type FtpReadCloser struct {
2017-05-03 12:18:17 +00:00
remote string
c *ftp.ServerConn
fd io.ReadCloser
2016-12-27 20:52:30 +00:00
}
/////////////////
// Url methods //
/////////////////
func (u *Url) ToDial() string {
return fmt.Sprintf("%s:%d", u.Host, u.Port)
}
func (u *Url) String() string {
return fmt.Sprintf("ftp://%s:%d/%s", u.Host, u.Port, u.Path)
}
func parseUrl(url string) Url {
// This is *similar* to the RFC 3986 regexp but it matches the
// port independently from the host
r, _ := regexp.Compile("^(([^:/?#]+):)?(//([^/?#:]*))?(:([0-9]+))?([^?#]*)(\\?([^#]*))?(#(.*))?")
2017-05-03 12:18:17 +00:00
2016-12-27 20:52:30 +00:00
data := r.FindAllStringSubmatch(url, -1)
2017-05-03 12:18:17 +00:00
if data[0][5] == "" {
data[0][5] = "21"
}
2016-12-27 20:52:30 +00:00
port, _ := strconv.Atoi(data[0][5])
return Url{data[0][2], data[0][4], port, data[0][7]}
}
////////////////
// Fs Methods //
////////////////
func (f *Fs) Put(in io.Reader, src fs.ObjectInfo) (fs.Object, error) {
2017-05-03 12:18:17 +00:00
fs.Debugf(f, "Trying to put file %s", src.Remote())
2016-12-27 20:52:30 +00:00
o := &Object{
2017-05-03 12:18:17 +00:00
fs: f,
2016-12-27 20:52:30 +00:00
remote: src.Remote(),
}
err := o.Update(in, src)
return o, err
}
func (f *Fs) Rmdir(dir string) error {
// This is actually a recursive remove directory
f.mu.Lock()
files, _ := f.c.List(filepath.Join(f.root, dir))
f.mu.Unlock()
2017-05-03 12:18:17 +00:00
for i := range files {
2016-12-27 20:52:30 +00:00
if files[i].Type == ftp.EntryTypeFolder {
f.Rmdir(filepath.Join(dir, files[i].Name))
}
2017-05-03 12:18:17 +00:00
}
2016-12-27 20:52:30 +00:00
f.mu.Lock()
err := f.c.RemoveDir(filepath.Join(f.root, dir))
f.mu.Unlock()
return err
}
func (f *Fs) Name() string {
2017-05-03 12:18:17 +00:00
return f.name
2016-12-27 20:52:30 +00:00
}
// Root of the remote (as passed into NewFs)
func (f *Fs) Root() string {
return f.root
}
func (f *Fs) String() string {
return fmt.Sprintf("FTP Connection to %s", f.url.String())
}
2017-05-03 12:18:17 +00:00
// Features returns the optional features of this Fs
func (f *Fs) Features() *fs.Features {
return f.features
}
2016-12-27 20:52:30 +00:00
// Hash are not supported
func (f *Fs) Hashes() fs.HashSet {
return 0
}
// Modified Time not supported
func (f *Fs) Precision() time.Duration {
return fs.ModTimeNotSupported
}
func (f *Fs) mkdir(abspath string) error {
_, err := f.GetInfo(abspath)
if err != nil {
2017-05-03 12:18:17 +00:00
fs.Debugf(f, "Trying to create directory %s", abspath)
2016-12-27 20:52:30 +00:00
f.mu.Lock()
err := f.c.MakeDir(abspath)
f.mu.Unlock()
if err != nil {
return err
}
}
2017-05-03 12:18:17 +00:00
return err
2016-12-27 20:52:30 +00:00
}
func (f *Fs) Mkdir(dir string) error {
// This actually works as mkdir -p
2017-05-03 12:18:17 +00:00
fs.Debugf(f, "ENTER function 'Mkdir' on '%s/%s'", f.root, dir)
defer fs.Debugf(f, "EXIT function 'Mkdir' on '%s/%s'", f.root, dir)
2016-12-27 20:52:30 +00:00
abspath := filepath.Join(f.root, dir)
tokens := strings.Split(abspath, "/")
curdir := ""
2017-05-03 12:18:17 +00:00
for i := range tokens {
2016-12-27 20:52:30 +00:00
curdir += "/" + tokens[i]
f.mkdir(curdir)
}
return nil
}
func (f *Fs) GetInfo(remote string) (*FileInfo, error) {
2017-05-03 12:18:17 +00:00
fs.Debugf(f, "ENTER function 'GetInfo' on file %s", remote)
defer fs.Debugf(f, "EXIT function 'GetInfo'")
2016-12-27 20:52:30 +00:00
dir := filepath.Dir(remote)
base := filepath.Base(remote)
f.mu.Lock()
files, _ := f.c.List(dir)
f.mu.Unlock()
2017-05-03 12:18:17 +00:00
for i := range files {
2016-12-27 20:52:30 +00:00
if files[i].Name == base {
info := &FileInfo{
2017-05-03 12:18:17 +00:00
Name: remote,
Size: files[i].Size,
2016-12-27 20:52:30 +00:00
ModTime: files[i].Time,
2017-05-03 12:18:17 +00:00
IsDir: files[i].Type == ftp.EntryTypeFolder,
2016-12-27 20:52:30 +00:00
}
return info, nil
}
}
return nil, fs.ErrorObjectNotFound
}
func (f *Fs) NewObject(remote string) (fs.Object, error) {
2017-05-03 12:18:17 +00:00
fs.Debugf(f, "ENTER function 'NewObject' called with remote %s", remote)
defer fs.Debugf(f, "EXIT function 'NewObject'")
2016-12-27 20:52:30 +00:00
dir := filepath.Dir(remote)
base := filepath.Base(remote)
f.mu.Lock()
files, _ := f.c.List(dir)
f.mu.Unlock()
2017-05-03 12:18:17 +00:00
for i := range files {
2016-12-27 20:52:30 +00:00
if files[i].Name == base {
o := &Object{
fs: f,
remote: remote,
}
info := &FileInfo{
2017-05-03 12:18:17 +00:00
Name: remote,
Size: files[i].Size,
2016-12-27 20:52:30 +00:00
ModTime: files[i].Time,
}
o.info = info
2017-05-03 12:18:17 +00:00
2016-12-27 20:52:30 +00:00
return o, nil
}
}
return nil, fs.ErrorObjectNotFound
}
2017-05-03 12:18:17 +00:00
func (f *Fs) list(out fs.ListOpts, dir string, curlevel int) {
fs.Debugf(f, "ENTER function 'list'")
defer fs.Debugf(f, "EXIT function 'list'")
2016-12-27 20:52:30 +00:00
f.mu.Lock()
files, _ := f.c.List(filepath.Join(f.root, dir))
f.mu.Unlock()
2017-05-03 12:18:17 +00:00
for i := range files {
2016-12-27 20:52:30 +00:00
object := files[i]
newremote := filepath.Join(dir, object.Name)
switch object.Type {
case ftp.EntryTypeFolder:
2017-05-03 12:18:17 +00:00
if out.IncludeDirectory(newremote) {
2016-12-27 20:52:30 +00:00
d := &fs.Dir{
Name: newremote,
When: object.Time,
Bytes: 0,
Count: -1,
}
2017-05-03 12:18:17 +00:00
if curlevel < out.Level() {
f.list(out, filepath.Join(dir, object.Name), curlevel+1)
2016-12-27 20:52:30 +00:00
}
if out.AddDir(d) {
return
}
}
default:
o := &Object{
fs: f,
remote: newremote,
}
info := &FileInfo{
2017-05-03 12:18:17 +00:00
Name: newremote,
Size: object.Size,
2016-12-27 20:52:30 +00:00
ModTime: object.Time,
}
o.info = info
if out.Add(o) {
return
}
}
}
}
func (f *Fs) List(out fs.ListOpts, dir string) {
2017-05-03 12:18:17 +00:00
fs.Debugf(f, "ENTER function 'List' on directory '%s/%s'", f.root, dir)
defer fs.Debugf(f, "EXIT function 'List' for directory '%s/%s'", f.root, dir)
2016-12-27 20:52:30 +00:00
f.list(out, dir, 1)
out.Finished()
}
////////////////////
// Object methods //
////////////////////
func (o *Object) Hash(t fs.HashType) (string, error) {
return "", fs.ErrHashUnsupported
}
func (o *Object) Open(options ...fs.OpenOption) (io.ReadCloser, error) {
path := filepath.Join(o.fs.root, o.remote)
2017-05-03 12:18:17 +00:00
fs.Debugf(o.fs, "ENTER function 'Open' on file '%s' in root '%s'", o.remote, o.fs.root)
defer fs.Debugf(o.fs, "EXIT function 'Open' %s", path)
2016-12-27 20:52:30 +00:00
c, _, err := ftpConnection(o.fs.name, o.fs.root)
if err != nil {
return nil, err
}
fd, err := c.Retr(path)
if err != nil {
return nil, err
}
return FtpReadCloser{path, c, fd}, nil
}
func (o *Object) Remote() string {
return o.remote
}
func (o *Object) Remove() error {
path := filepath.Join(o.fs.root, o.remote)
2017-05-03 12:18:17 +00:00
fs.Debugf(o, "ENTER function 'Remove' for obejct at %s", path)
defer fs.Debugf(o, "EXIT function 'Remove' for obejct at %s", path)
2016-12-27 20:52:30 +00:00
// Check if it's a directory or a file
info, _ := o.fs.GetInfo(path)
var err error
if info.IsDir {
err = o.fs.Rmdir(o.remote)
} else {
o.fs.mu.Lock()
err = o.fs.c.Delete(path)
o.fs.mu.Unlock()
}
return err
}
func (o *Object) SetModTime(modTime time.Time) error {
return nil
}
func (o *Object) Fs() fs.Info {
return o.fs
}
func (o *Object) ModTime() time.Time {
return o.info.ModTime
}
func (o *Object) Size() int64 {
return int64(o.info.Size)
}
func (o *Object) Storable() bool {
return true
}
func (o *Object) String() string {
return fmt.Sprintf("FTP file at %s/%s", o.fs.url.String(), o.remote)
}
func (o *Object) MakeAllDir() {
tokens := strings.Split(filepath.Dir(o.remote), "/")
dir := ""
2017-05-03 12:18:17 +00:00
for i := range tokens {
dir += tokens[i] + "/"
2016-12-27 20:52:30 +00:00
o.fs.Mkdir(dir)
}
}
func (o *Object) Update(in io.Reader, src fs.ObjectInfo) error {
// Create all upper directory first...
o.MakeAllDir()
path := filepath.Join(o.fs.root, o.remote)
c, _, _ := ftpConnection(o.fs.name, o.fs.root)
err := c.Stor(path, in)
o.info, _ = o.fs.GetInfo(path)
return err
}
///////////////////////////
// FtpReadCloser methods //
///////////////////////////
func (f FtpReadCloser) Read(p []byte) (int, error) {
return f.fd.Read(p)
}
func (f FtpReadCloser) Close() error {
err := f.fd.Close()
defer f.c.Quit()
if err != nil {
return nil
}
return nil
}
// This mutex is only used by ftpConnection. We create a new ftp
// connection for each transfer, but we need to serialize it otherwise
// Dial() and Login() might be mixed...
var globalMux = sync.Mutex{}
func ftpConnection(name, root string) (*ftp.ServerConn, Url, error) {
// Open a new connection to the FTP server.
url := fs.ConfigFileGet(name, "url")
user := fs.ConfigFileGet(name, "username")
pass := fs.ConfigFileGet(name, "password")
u := parseUrl(url)
u.Path = filepath.Join(u.Path, root)
2017-05-03 12:18:17 +00:00
fs.Debugf(nil, "New ftp Connection with name %s and url %s (path %s)", name, u.String(), u.Path)
2016-12-27 20:52:30 +00:00
globalMux.Lock()
defer globalMux.Unlock()
c, err := ftp.DialTimeout(u.ToDial(), 30*time.Second)
if err != nil {
2017-05-03 12:18:17 +00:00
fs.Errorf(nil, "Error while Dialing %s: %s", u.ToDial(), err)
2016-12-27 20:52:30 +00:00
return nil, u, err
}
err = c.Login(user, pass)
if err != nil {
2017-05-03 12:18:17 +00:00
fs.Errorf(nil, "Error while Logging in into %s: %s", u.ToDial(), err)
2016-12-27 20:52:30 +00:00
return nil, u, err
}
return c, u, nil
}
// Register the FS
func NewFs(name, root string) (fs.Fs, error) {
2017-05-03 12:18:17 +00:00
fs.Debugf(nil, "ENTER function 'NewFs' with name %s and root %s", name, root)
defer fs.Debugf(nil, "EXIT function 'NewFs'")
2016-12-27 20:52:30 +00:00
c, u, err := ftpConnection(name, root)
if err != nil {
return nil, err
}
2017-05-03 12:18:17 +00:00
f := &Fs{
2016-12-27 20:52:30 +00:00
name: name,
root: u.Path,
2017-05-03 12:18:17 +00:00
c: c,
url: u,
mu: sync.Mutex{},
2016-12-27 20:52:30 +00:00
}
2017-05-03 12:18:17 +00:00
f.features = (&fs.Features{}).Fill(f)
return f, err
2016-12-27 20:52:30 +00:00
}
2017-05-03 12:18:17 +00:00
// Check the interfaces are satisfied
2016-12-27 20:52:30 +00:00
var (
2017-05-03 12:18:17 +00:00
_ fs.Fs = &Fs{}
_ fs.Object = &Object{}
2016-12-27 20:52:30 +00:00
)