-
Notifications
You must be signed in to change notification settings - Fork 1
/
ftp.go
124 lines (115 loc) · 2.22 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
122
123
124
package sc
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type FTPCombinator struct {
host, user, password string
}
func NewFTPCombinator(host, user, password string) (*FTPCombinator, error) {
ftp := &FTPCombinator{
host: host,
user: user,
password: password,
}
return ftp, nil
}
func (f FTPCombinator) login() (*sftp.Client, error) {
config := &ssh.ClientConfig{
User: f.user,
Auth: []ssh.AuthMethod{
ssh.Password(f.password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", f.host), config)
if err != nil {
return nil, err
}
return sftp.NewClient(conn)
}
type Listing struct {
Name string
Size int64
ModTime time.Time
Mode string
IsDir bool
}
func NewListing(fi os.FileInfo) Listing {
return Listing{
Name: fi.Name(),
Size: fi.Size(),
ModTime: fi.ModTime(),
Mode: fi.Mode().String(),
IsDir: fi.IsDir(),
}
}
func (f FTPCombinator) Get(r Reference) (interface{}, error) {
s, err := f.login()
if err != nil {
return nil, err
}
defer s.Close()
u := r.URI()
p := u.Path
for {
if !strings.HasPrefix(p, "/") {
break
}
p = p[1:]
}
list := func(dir string) (interface{}, error) {
w := new(bytes.Buffer)
e := json.NewEncoder(w)
e.SetEscapeHTML(false)
list, err := s.ReadDir(p)
if err != nil {
return nil, err
}
for _, fi := range list {
if err := e.Encode(NewListing(fi)); err != nil {
return nil, err
}
}
return w.Bytes(), nil
}
if len(p) == 0 {
return list(".")
}
file, err := s.Open(p)
if err != nil {
return nil, err
}
fi, err := file.Stat()
if err != nil {
return nil, err
}
if fi.IsDir() {
return list(p)
}
w := new(bytes.Buffer)
n, err := io.Copy(w, file)
if err != nil {
return nil, err
}
if n != fi.Size() {
return nil, fmt.Errorf("expected %d bytes, got %d", fi.Size(), n)
}
return w.Bytes(), nil
}
func (f FTPCombinator) Put(Reference, interface{}) error {
return unimplemented(f, "Put")
}
func (f FTPCombinator) Delete(Reference) error {
return unimplemented(f, "Delete")
}
func (f FTPCombinator) Merge(Reference, interface{}) error {
return unimplemented(f, "Merge")
}