/
client.go
485 lines (373 loc) · 9.64 KB
/
client.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package sftp
import (
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/nethack42/go-sftp/sshfxp"
)
type Client struct {
reader io.ReadCloser
writer io.WriteCloser
incoming chan sshfxp.Packet
outgoing chan sshfxp.Packet
errch chan error
ioErr error
router *Router
version uint32
wg sync.WaitGroup
}
type ClientConn interface {
OpenDir(string) (string, error)
Open(string, uint32, os.FileInfo) (string, error)
ReadDir(string) ([]os.FileInfo, error)
List(string) ([]os.FileInfo, error)
Close(string) error
Read(string, uint64, uint32) ([]byte, error)
Write(string, uint64, []byte) error
MkDir(string, os.FileInfo) error
RmDir(string) error
FileReader(string) (io.Reader, error)
FileWriter(string) (io.WriteCloser, error)
Put(string, string) error
Get(string, string) error
Rename(string, string) error
Remove(string) error
}
var _ ClientConn = &Client{}
func NewClient(r io.ReadCloser, w io.WriteCloser) *Client {
cli := &Client{
reader: r,
writer: w,
incoming: make(chan sshfxp.Packet),
outgoing: make(chan sshfxp.Packet),
router: NewRouter(),
errch: make(chan error, 2), // one error per goroutine
}
cli.wg.Add(2)
go func(cli *Client) {
defer cli.wg.Done()
defer logrus.Infof("SFTP client writer exited")
cli.errch <- writeConn(cli.writer, cli.outgoing)
}(cli)
go func(cli *Client) {
defer cli.wg.Done()
defer logrus.Infof("SFTP client reader exited")
cli.errch <- readConn(cli.reader, cli.incoming)
}(cli)
if err := cli.DoHandshake(); err != nil {
logrus.Errorf("SFTP handshake failed: %s", err)
// Close outgoing
close(cli.outgoing)
cli.reader.Close()
cli.writer.Close()
cli.wg.Wait()
cli.ioErr = err
return nil
}
logrus.Infof("SFTP-handeshake complete. Using SFTP version %d", cli.version)
cli.wg.Add(1)
go func(cli *Client) {
defer cli.wg.Done()
L:
for {
select {
case msg := <-cli.incoming:
// TODO we currently ignore any error from message handling
if err := cli.handleMessage(msg); err != nil {
logrus.Errorf("failed to handle message: %s", err)
}
case err := <-cli.errch:
if err != nil {
cli.ioErr = err
logrus.Errorf("received error: %s", err)
}
logrus.Infof("received nil on errch")
break L
}
}
close(cli.outgoing) // will cause writer to stop if it hasn't already
}(cli)
return cli
}
// Wait waits for hte cient goroutines to finish
func (cli *Client) Wait() {
cli.wg.Wait()
}
// DoHandshake establishes a new SFTP connection and performs the initial
// handshake. The protocol version in use can afterwards be retrieved using the
// Version method
func (cli *Client) DoHandshake() error {
init := &sshfxp.Init{
Version: 3,
}
if _, err := cli.send(init); err != nil {
return err
}
pkt := <-cli.incoming
msg, err := pkt.Decode()
if err != nil {
return err
}
if version, ok := msg.(*sshfxp.Version); !ok {
return errors.New("unexpected message received")
} else {
if version.Version != init.Version {
return errors.New("unsupported version")
}
cli.version = version.Version
}
return nil
}
// Version returns the SFTP version used. The result is only valid after
// DoHandshake as been called
func (cli *Client) Version() uint32 {
return cli.version
}
// OpenDir opens a handle to the directory identified by path
func (cli *Client) OpenDir(path string) (string, error) {
open := &sshfxp.OpenDir{
Path: path,
}
var err error
var res_chan <-chan sshfxp.Message
if res_chan, err = cli.send(open); err != nil {
return "", err
}
// wait for result
var res interface{} = <-res_chan
if err := sshfxp.IsError(res); err != nil {
return "", err
}
switch msg := res.(type) {
case *sshfxp.Handle:
return msg.Handle, nil
}
return "", fmt.Errorf("open_dir: unexpected response: %#v", res)
}
// ReadDir reads directory contents for the given handle and returns a list
// of os.FileInfo
func (cli *Client) ReadDir(handle string) ([]os.FileInfo, error) {
read := &sshfxp.ReadDir{
Handle: handle,
}
resCh, err := cli.send(read)
if err != nil {
return nil, err
}
res := <-resCh
if err := sshfxp.IsError(res); err != nil {
return nil, err
}
switch msg := res.(type) {
case *sshfxp.Name:
var res []os.FileInfo
for _, name := range msg.Names {
res = append(res, FileInfo{
name: name.Filename,
size: int64(name.Attr.Size),
mode: os.FileMode(name.Attr.Permissions),
modtime: time.Unix(int64(name.Attr.MTime), 0),
packet: name,
})
}
return res, nil
}
return nil, errors.New("unexpected response")
}
// Close closes the given file or directory handle
func (cli *Client) Close(handle string) error {
close := &sshfxp.Close{
Handle: handle,
}
resCh, err := cli.send(close)
if err != nil {
return err
}
if err := sshfxp.IsError(<-resCh); err != nil {
return err
}
return nil
}
// List returns a list of files and directories in a given path. List wraps
// calles to OpenDir, ReadDir and Close
func (cli *Client) List(path string) ([]os.FileInfo, error) {
handle, err := cli.OpenDir(path)
if err != nil {
return nil, err
}
defer cli.Close(handle)
return cli.ReadDir(handle)
}
// Open opens the file identifided by path using the access mode specified in
// flags. If the file is going to be created, attr can hold additional file
// attributes.
//
// BUG: flags and attr is currently not supported
func (cli *Client) Open(path string, flags uint32, attr os.FileInfo) (string, error) {
open := &sshfxp.Open{
Filename: path,
PFlags: flags,
Attributes: sshfxp.Attr{}, // TODO: not yet supported
}
resCh, err := cli.send(open)
if err != nil {
return "", err
}
res := <-resCh
if err := sshfxp.IsError(res); err != nil {
return "", err
}
switch msg := res.(type) {
case *sshfxp.Handle:
return msg.Handle, nil
}
return "", errors.New("unexpected response")
}
// Read reads `length` bytes of data from the file identified by handle and
// starting at offset. The file handle must have been acquired previously by
// calling Open()
func (cli *Client) Read(handle string, offset uint64, length uint32) ([]byte, error) {
read := &sshfxp.Read{
Handle: handle,
Offset: offset,
Length: length,
}
resCh, err := cli.send(read)
if err != nil {
return nil, err
}
res := <-resCh
if err := sshfxp.IsError(res); err != nil {
return nil, err
}
switch msg := res.(type) {
case *sshfxp.Data:
return []byte(msg.Data), nil
}
return nil, errors.New("unexpected response")
}
// Write writes the given slice of data to the file identified by handle starting
// at offset. The file handle must have been acquired previously by calling
// Open()
func (cli *Client) Write(handle string, offset uint64, data []byte) error {
write := &sshfxp.Write{
Handle: handle,
Offset: offset,
Data: string(data),
}
resCh, err := cli.send(write)
if err != nil {
return err
}
if err := sshfxp.IsError(<-resCh); err != nil {
return err
}
return nil
}
// Remove removes the file identified by path.
func (cli *Client) Remove(path string) error {
if resCh, err := cli.send(&sshfxp.Remove{File: path}); err != nil {
return err
} else if err := sshfxp.IsError(<-resCh); err != nil {
return err
}
return nil
}
// Rename renames the file or directory identified by oldPath to newPath
func (cli *Client) Rename(oldPath, newPath string) error {
if resCh, err := cli.send(&sshfxp.Rename{OldPath: oldPath, NewPath: newPath}); err != nil {
return err
} else if err := sshfxp.IsError(<-resCh); err != nil {
return err
}
return nil
}
// MkDir creates the directory path using os.FileInfo attributes
func (cli *Client) MkDir(path string, attr os.FileInfo) error {
mkdir := &sshfxp.MkDir{
Path: path,
Attr: sshfxp.Attr{},
}
if resCh, err := cli.send(mkdir); err != nil {
return err
} else if err := sshfxp.IsError(<-resCh); err != nil {
return err
}
return nil
}
// RmDir removes the directory path
func (cli *Client) RmDir(path string) error {
if resCh, err := cli.send(&sshfxp.RmDir{Path: path}); err != nil {
return err
} else if err := sshfxp.IsError(<-resCh); err != nil {
return err
}
return nil
}
func (cli *Client) send(x sshfxp.Message) (<-chan sshfxp.Message, error) {
var pkt sshfxp.Packet
var res <-chan sshfxp.Message
if header, ok := (interface{}(x)).(sshfxp.Header); ok {
id, ch := cli.router.Get()
header.SetID(id)
res = ch
}
if err := pkt.Encode(x); err != nil {
return nil, err
}
cli.outgoing <- pkt
return res, nil
}
func (cli *Client) handleMessage(msg sshfxp.Packet) error {
payload, err := msg.Decode()
if err != nil {
return fmt.Errorf("failed to decode message: %s", err)
}
if err := cli.router.Resolve(payload); err != nil {
return err
}
return nil
}
// FileReader returns an io.Reader attached to the remote file identifed by
// path
func (cli *Client) FileReader(path string) (io.Reader, error) {
return NewFileReader(path, cli)
}
// FileWriter returns an io.WriteCloser attached to the remote file identified
// by path
func (cli *Client) FileWriter(path string) (io.WriteCloser, error) {
return NewFileWriter(path, cli)
}
// Put uploads a local file identified by local to remote
func (cli *Client) Put(local, remote string) error {
rw, err := cli.FileWriter(remote)
if err != nil {
return err
}
defer rw.Close()
f, err := os.Open(local)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(rw, f)
return err
}
// Get downloads the remote file `remote` and stores it underl `local`
func (cli *Client) Get(remote, local string) error {
r, err := cli.FileReader(remote)
if err != nil {
return err
}
f, err := os.Create(local)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, r)
return err
}