/
ftp.go
121 lines (101 loc) · 2.42 KB
/
ftp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package dirsync
import (
"io"
"os"
"path"
"strings"
"github.com/jlaffaye/ftp"
)
type FTPConfig struct {
Host string
User string
Pass string
}
// FTP is a Lister and Downloader which operates on a remote host.
type FTP struct {
config FTPConfig
connection *ftp.ServerConn
}
// NewFTP creates a new FTP instance using a given configuration.
// It will not automatically connect to the remote end.
func NewFTP(c FTPConfig) *FTP {
return &FTP{c, nil}
}
// Disconnect shuts down the FTP connection.
func (f *FTP) Disconnect() {
if f.connection != nil {
f.connection.Quit()
f.connection = nil
}
}
// List returns the contents of a directory.
// If the connection fails, this returns an error.
func (f *FTP) List(dir string) ([]FileInfo, error) {
if err := f.ensureConnected(); err != nil {
return nil, err
}
entries, err := f.connection.List(dir)
if err != nil {
f.Disconnect()
return nil, err
}
res := make([]FileInfo, len(entries))
for i, entry := range entries {
// NOTE: if the FTP server is compromised, they could theoretically
// do something malicious like give a "filename" with a / in it.
// I don't trust the FTP library to prevent against these situations.
if strings.ContainsRune(entry.Name, '/') {
panic("invalid filename: " + entry.Name)
}
res[i] = FileInfo{
Path: path.Join(dir, entry.Name),
IsDir: entry.Type == ftp.EntryTypeFolder,
FileSize: entry.Size,
}
}
return res, nil
}
// Download gets a remote file and stores it at a local path.
// If the connection fails or the local file cannot be written, this returns an error.
func (f *FTP) Download(remotePath, localPath string) error {
if err := f.ensureConnected(); err != nil {
return err
}
reader, err := f.connection.Retr(remotePath)
if err != nil {
return err
}
defer reader.Close()
file, err := os.Create(localPath)
if err != nil {
return err
}
defer file.Close()
if _, err := io.Copy(file, reader); err != nil {
os.Remove(localPath)
return err
}
return nil
}
func (f *FTP) ensureConnected() error {
if f.connection != nil {
if f.connection.NoOp() != nil {
f.Disconnect()
}
}
if f.connection == nil {
return f.connect()
}
return nil
}
func (f *FTP) connect() error {
var err error
if f.connection, err = ftp.Connect(f.config.Host); err != nil {
return err
}
if err = f.connection.Login(f.config.User, f.config.Pass); err != nil {
f.Disconnect()
return err
}
return nil
}