/
client.go
644 lines (607 loc) · 14.4 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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
package sftp
import (
"io"
"os"
"path"
"path/filepath"
"sync"
"code.google.com/p/go.crypto/ssh"
)
// New creates a new SFTP client on conn.
func NewClient(conn *ssh.ClientConn) (*Client, error) {
s, err := conn.NewSession()
if err != nil {
return nil, err
}
if err := s.RequestSubsystem("sftp"); err != nil {
return nil, err
}
pw, err := s.StdinPipe()
if err != nil {
return nil, err
}
pr, err := s.StdoutPipe()
if err != nil {
return nil, err
}
sftp := &Client{
w: pw,
r: pr,
}
if err := sftp.sendInit(); err != nil {
return nil, err
}
return sftp, sftp.recvVersion()
}
// Client represents an SFTP session on a *ssh.ClientConn SSH connection.
// Multiple Clients can be active on a single SSH connection, and a Client
// may be called concurrently from multiple Goroutines.
type Client struct {
w io.WriteCloser
r io.Reader
mu sync.Mutex // locks mu and seralises commands to the server
nextid uint32
}
// Close closes the SFTP session.
func (c *Client) Close() error { return c.w.Close() }
// Create creates the named file mode 0666 (before umask), truncating it if
// it already exists. If successful, methods on the returned File can be
// used for I/O; the associated file descriptor has mode O_RDWR.
func (c *Client) Create(path string) (*File, error) {
return c.open(path, ssh_FXF_READ|ssh_FXF_WRITE|ssh_FXF_CREAT|ssh_FXF_TRUNC)
}
func (c *Client) sendInit() error {
type packet struct {
Type byte
Version uint32
Extensions []struct {
Name, Data string
}
}
return sendPacket(c.w, packet{
Type: ssh_FXP_INIT,
Version: 3, // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02
})
}
// returns the current value of c.nextid and increments it
// callers is expected to hold c.mu
func (c *Client) nextId() uint32 {
v := c.nextid
c.nextid++
return v
}
func (c *Client) recvVersion() error {
typ, _, err := recvPacket(c.r)
if err != nil {
return err
}
if typ != ssh_FXP_VERSION {
return &unexpectedPacketErr{ssh_FXP_VERSION, typ}
}
return nil
}
// Walk returns a new Walker rooted at root.
func (c *Client) Walk(root string) *Walker {
info, err := c.Lstat(root)
return &Walker{c: c, stack: []item{{root, info, err}}}
}
func (c *Client) readDir(p string) ([]os.FileInfo, error) {
handle, err := c.opendir(p)
if err != nil {
return nil, err
}
var attrs []os.FileInfo
c.mu.Lock()
defer c.mu.Unlock()
var done = false
for !done {
type packet struct {
Type byte
Id uint32
Handle string
}
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_READDIR,
Id: id,
Handle: handle,
}); err != nil {
return nil, err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return nil, err
}
switch typ {
case ssh_FXP_NAME:
sid, data := unmarshalUint32(data)
if sid != id {
return nil, &unexpectedIdErr{id, sid}
}
count, data := unmarshalUint32(data)
for i := uint32(0); i < count; i++ {
var filename string
filename, data = unmarshalString(data)
_, data = unmarshalString(data) // discard longname
var attr *attr
attr, data = unmarshalAttrs(data)
if filename == "." || filename == ".." {
continue
}
attr.name = path.Base(filename)
attrs = append(attrs, attr)
}
case ssh_FXP_STATUS:
sid, data := unmarshalUint32(data)
if sid != id {
return nil, &unexpectedIdErr{id, sid}
}
code, data := unmarshalUint32(data)
msg, data := unmarshalString(data)
lang, _ := unmarshalString(data)
err = &StatusError{
Code: code,
msg: msg,
lang: lang,
}
done = true
default:
return nil, unimplementedPacketErr(typ)
}
}
// TODO(dfc) closedir
return attrs, err
}
func (c *Client) opendir(path string) (string, error) {
type packet struct {
Type byte
Id uint32
Path string
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_OPENDIR,
Id: id,
Path: path,
}); err != nil {
return "", err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return "", err
}
switch typ {
case ssh_FXP_HANDLE:
sid, data := unmarshalUint32(data)
if sid != id {
return "", &unexpectedIdErr{id, sid}
}
handle, _ := unmarshalString(data)
return handle, nil
case ssh_FXP_STATUS:
return "", unmarshalStatus(id, data)
default:
return "", unimplementedPacketErr(typ)
}
}
func (c *Client) Lstat(p string) (os.FileInfo, error) {
type packet struct {
Type byte
Id uint32
Path string
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_LSTAT,
Id: id,
Path: p,
}); err != nil {
return nil, err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return nil, err
}
switch typ {
case ssh_FXP_ATTRS:
sid, data := unmarshalUint32(data)
if sid != id {
return nil, &unexpectedIdErr{id, sid}
}
attr, _ := unmarshalAttrs(data)
attr.name = path.Base(p)
return attr, nil
case ssh_FXP_STATUS:
return nil, unmarshalStatus(id, data)
default:
return nil, unimplementedPacketErr(typ)
}
}
// Open opens the named file for reading. If successful, methods on the
// returned file can be used for reading; the associated file descriptor
// has mode O_RDONLY.
func (c *Client) Open(path string) (*File, error) {
return c.open(path, ssh_FXF_READ)
}
func (c *Client) open(path string, pflags uint32) (*File, error) {
type packet struct {
Type byte
Id uint32
Path string
Pflags uint32
Flags uint32 // ignored
Size uint64 // ignored
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_OPEN,
Id: id,
Path: path,
Pflags: pflags,
}); err != nil {
return nil, err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return nil, err
}
switch typ {
case ssh_FXP_HANDLE:
sid, data := unmarshalUint32(data)
if sid != id {
return nil, &unexpectedIdErr{id, sid}
}
handle, _ := unmarshalString(data)
return &File{c: c, path: path, handle: handle}, nil
case ssh_FXP_STATUS:
return nil, unmarshalStatus(id, data)
default:
return nil, unimplementedPacketErr(typ)
}
}
// readAt reads len(buf) bytes from the remote file indicated by handle starting
// from offset.
func (c *Client) readAt(handle string, offset uint64, buf []byte) (uint32, error) {
type packet struct {
Type byte
Id uint32
Handle string
Offset uint64
Len uint32
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_READ,
Id: id,
Handle: handle,
Offset: offset,
Len: uint32(len(buf)),
}); err != nil {
return 0, err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return 0, err
}
switch typ {
case ssh_FXP_DATA:
sid, data := unmarshalUint32(data)
if sid != id {
return 0, &unexpectedIdErr{id, sid}
}
l, data := unmarshalUint32(data)
n := copy(buf, data[:l])
return uint32(n), nil
case ssh_FXP_STATUS:
return 0, eofOrErr(unmarshalStatus(id, data))
default:
return 0, unimplementedPacketErr(typ)
}
}
// close closes a handle handle previously returned in the response
// to SSH_FXP_OPEN or SSH_FXP_OPENDIR. The handle becomes invalid
// immediately after this request has been sent.
func (c *Client) close(handle string) error {
type packet struct {
Type byte
Id uint32
Handle string
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_CLOSE,
Id: id,
Handle: handle,
}); err != nil {
return err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return err
}
switch typ {
case ssh_FXP_STATUS:
return okOrErr(unmarshalStatus(id, data))
default:
return unimplementedPacketErr(typ)
}
}
func (c *Client) fstat(handle string) (*attr, error) {
type packet struct {
Type byte
Id uint32
Handle string
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_FSTAT,
Id: id,
Handle: handle,
}); err != nil {
return nil, err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return nil, err
}
switch typ {
case ssh_FXP_ATTRS:
sid, data := unmarshalUint32(data)
if sid != id {
return nil, &unexpectedIdErr{id, sid}
}
attr, _ := unmarshalAttrs(data)
return attr, nil
case ssh_FXP_STATUS:
return nil, unmarshalStatus(id, data)
default:
return nil, unimplementedPacketErr(typ)
}
}
// Remove removes the named file or directory.
func (c *Client) Remove(path string) error {
// TODO(dfc) can't handle directories, yet
type packet struct {
Type byte
Id uint32
Filename string
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_REMOVE,
Id: id,
Filename: path,
}); err != nil {
return err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return err
}
switch typ {
case ssh_FXP_STATUS:
return okOrErr(unmarshalStatus(id, data))
default:
return unimplementedPacketErr(typ)
}
}
// Rename renames a file.
func (c *Client) Rename(oldname, newname string) error {
type packet struct {
Type byte
Id uint32
Oldpath, Newpath string
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_RENAME,
Id: id,
Oldpath: oldname,
Newpath: newname,
}); err != nil {
return err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return err
}
switch typ {
case ssh_FXP_STATUS:
return okOrErr(unmarshalStatus(id, data))
default:
return unimplementedPacketErr(typ)
}
}
// writeAt writes len(buf) bytes from the remote file indicated by handle starting
// from offset.
func (c *Client) writeAt(handle string, offset uint64, buf []byte) (uint32, error) {
type packet struct {
Type byte
Id uint32
Handle string
Offset uint64
Length uint32
Data []byte
}
c.mu.Lock()
defer c.mu.Unlock()
id := c.nextId()
if err := sendPacket(c.w, packet{
Type: ssh_FXP_WRITE,
Id: id,
Handle: handle,
Offset: offset,
Length: uint32(len(buf)),
Data: buf,
}); err != nil {
return 0, err
}
typ, data, err := recvPacket(c.r)
if err != nil {
return 0, err
}
switch typ {
case ssh_FXP_STATUS:
if err := okOrErr(unmarshalStatus(id, data)); err != nil {
return 0, nil
}
return uint32(len(buf)), nil
default:
return 0, unimplementedPacketErr(typ)
}
}
// File represents a remote file.
type File struct {
c *Client
path string
handle string
offset uint64 // current offset within remote file
}
// Close closes the File, rendering it unusable for I/O. It returns an
// error, if any.
func (f *File) Close() error {
return f.c.close(f.handle)
}
// Read reads up to len(b) bytes from the File. It returns the number of
// bytes read and an error, if any. EOF is signaled by a zero count with
// err set to io.EOF.
func (f *File) Read(b []byte) (int, error) {
n, err := f.c.readAt(f.handle, f.offset, b)
f.offset += uint64(n)
return int(n), err
}
// ReadAt reads len(b) bytes from the File starting at byte offset off. It
// returns the number of bytes read and the error, if any. ReadAt always
// returns a non-nil error when n < len(b). At end of file, that error is
// io.EOF.
func (f *File) ReadAt(b []byte, off int64) (int, error) {
n, err := f.c.readAt(f.handle, uint64(off), b)
return int(n), err
}
// Stat returns the FileInfo structure describing file. If there is an
// error.
func (f *File) Stat() (os.FileInfo, error) {
fi, err := f.c.fstat(f.handle)
if err == nil {
fi.name = path.Base(f.path)
}
return fi, err
}
// Write writes len(b) bytes to the File. It returns the number of bytes
// written and an error, if any. Write returns a non-nil error when n !=
// len(b).
func (f *File) Write(b []byte) (int, error) {
n, err := f.c.writeAt(f.handle, f.offset, b)
f.offset += uint64(n)
return int(n), err
}
// Walker provides a convenient interface for iterating over the
// descendants of a filesystem path.
// Successive calls to the Step method will step through each
// file or directory in the tree, including the root. The files
// are walked in lexical order, which makes the output deterministic
// but means that for very large directories Walker can be inefficient.
// Walker does not follow symbolic links.
type Walker struct {
c *Client
cur item
stack []item
descend bool
}
// Err returns the error, if any, for the most recent attempt
// by Step to visit a file or directory. If a directory has
// an error, w will not descend into that directory.
func (w *Walker) Err() error {
return w.cur.err
}
// Path returns the path to the most recent file or directory
// visited by a call to Step. It contains the argument to Walk
// as a prefix; that is, if Walk is called with "dir", which is
// a directory containing the file "a", Path will return "dir/a".
func (w *Walker) Path() string {
return w.cur.path
}
// Stat returns info for the most recent file or directory
// visited by a call to Step.
func (w *Walker) Stat() os.FileInfo {
return w.cur.info
}
// Step advances the Walker to the next file or directory,
// which will then be available through the Path, Stat,
// and Err methods.
// It returns false when the walk stops at the end of the tree.
func (w *Walker) Step() bool {
if w.descend && w.cur.err == nil && w.cur.info.IsDir() {
list, err := w.c.readDir(w.cur.path)
if err != nil {
w.cur.err = err
w.stack = append(w.stack, w.cur)
} else {
for i := len(list) - 1; i >= 0; i-- {
path := filepath.Join(w.cur.path, list[i].Name())
w.stack = append(w.stack, item{path, list[i], nil})
}
}
}
if len(w.stack) == 0 {
return false
}
i := len(w.stack) - 1
w.cur = w.stack[i]
w.stack = w.stack[:i]
w.descend = true
return true
}
// SkipDir causes the currently visited directory to be skipped.
// If w is not on a directory, SkipDir has no effect.
func (w *Walker) SkipDir() {
w.descend = false
}
type item struct {
path string
info os.FileInfo
err error
}
// okOrErr returns nil if Err.Code is SSH_FX_OK, otherwise it returns the error.
func okOrErr(err error) error {
if err, ok := err.(*StatusError); ok && err.Code == ssh_FX_OK {
return nil
}
return err
}
func eofOrErr(err error) error {
if err, ok := err.(*StatusError); ok && err.Code == ssh_FX_EOF {
return io.EOF
}
return err
}
func unmarshalStatus(id uint32, data []byte) error {
sid, data := unmarshalUint32(data)
if sid != id {
return &unexpectedIdErr{id, sid}
}
code, data := unmarshalUint32(data)
msg, data := unmarshalString(data)
lang, _ := unmarshalString(data)
return &StatusError{
Code: code,
msg: msg,
lang: lang,
}
}