sftp/client.go

645 lines
14 KiB
Go
Raw Normal View History

package sftp
import (
"io"
"os"
2013-11-06 12:40:35 +08:00
"path"
"path/filepath"
"sync"
"code.google.com/p/go.crypto/ssh"
)
2013-11-06 11:50:04 +08:00
// 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()
}
2013-11-06 10:04:40 +08:00
// 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
}
2013-11-06 10:04:40 +08:00
// Close closes the SFTP session.
func (c *Client) Close() error { return c.w.Close() }
2013-11-06 10:04:40 +08:00
// 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}}}
}
2013-11-06 12:40:35 +08:00
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
}
2013-11-06 12:40:35 +08:00
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:
2013-11-06 11:50:04 +08:00
return "", unmarshalStatus(id, data)
default:
return "", unimplementedPacketErr(typ)
}
}
2013-11-06 12:40:35 +08:00
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,
2013-11-06 12:40:35 +08:00
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)
2013-11-06 12:40:35 +08:00
attr.name = path.Base(p)
return attr, nil
case SSH_FXP_STATUS:
2013-11-06 11:50:04 +08:00
return nil, unmarshalStatus(id, data)
default:
return nil, unimplementedPacketErr(typ)
}
}
2013-11-06 08:04:26 +08:00
// 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) {
2013-11-06 09:53:45 +08:00
return c.open(path, SSH_FXF_READ)
}
func (c *Client) open(path string, pflags uint32) (*File, error) {
2013-11-06 08:04:26 +08:00
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,
2013-11-06 09:53:45 +08:00
Pflags: pflags,
2013-11-06 08:04:26 +08:00
}); 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)
2013-11-06 09:36:05 +08:00
return &File{c: c, path: path, handle: handle}, nil
2013-11-06 08:04:26 +08:00
case SSH_FXP_STATUS:
2013-11-06 11:50:04 +08:00
return nil, unmarshalStatus(id, data)
2013-11-06 08:04:26 +08:00
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}
}
2013-11-06 12:53:14 +08:00
l, data := unmarshalUint32(data)
n := copy(buf, data[:l])
2013-11-06 08:04:26 +08:00
return uint32(n), nil
case SSH_FXP_STATUS:
2013-11-06 12:53:14 +08:00
return 0, eofOrErr(unmarshalStatus(id, data))
2013-11-06 08:04:26 +08:00
default:
return 0, unimplementedPacketErr(typ)
}
}
2013-11-06 08:30:01 +08:00
// 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:
2013-11-06 11:50:04 +08:00
return okOrErr(unmarshalStatus(id, data))
2013-11-06 08:30:01 +08:00
default:
return unimplementedPacketErr(typ)
}
}
2013-11-06 09:36:05 +08:00
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:
2013-11-06 11:50:04 +08:00
return nil, unmarshalStatus(id, data)
2013-11-06 09:36:05 +08:00
default:
return nil, unimplementedPacketErr(typ)
}
}
2013-11-06 09:42:14 +08:00
2013-11-06 11:08:26 +08:00
// 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:
2013-11-06 11:50:04 +08:00
return okOrErr(unmarshalStatus(id, data))
2013-11-06 11:08:26 +08:00
default:
return unimplementedPacketErr(typ)
}
}
2013-11-06 11:15:26 +08:00
// 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)
}
}
2013-11-06 10:04:40 +08:00
// 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
2013-11-06 13:09:06 +08:00
Length uint32
2013-11-06 10:04:40 +08:00
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,
2013-11-06 13:09:06 +08:00
Length: uint32(len(buf)),
2013-11-06 10:04:40 +08:00
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:
2013-11-06 11:50:04 +08:00
if err := okOrErr(unmarshalStatus(id, data)); err != nil {
return 0, nil
2013-11-06 10:04:40 +08:00
}
return uint32(len(buf)), nil
default:
return 0, unimplementedPacketErr(typ)
}
}
2013-11-06 09:42:14 +08:00
// File represents a remote file.
type File struct {
2013-11-06 09:53:45 +08:00
c *Client
path string
handle string
offset uint64 // current offset within remote file
2013-11-06 09:42:14 +08:00
}
// Close closes the File, rendering it unusable for I/O. It returns an
// error, if any.
func (f *File) Close() error {
2013-11-06 09:53:45 +08:00
return f.c.close(f.handle)
2013-11-06 09:42:14 +08:00
}
// 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) {
2013-11-06 09:53:45 +08:00
n, err := f.c.readAt(f.handle, f.offset, b)
f.offset += uint64(n)
return int(n), err
2013-11-06 09:42:14 +08:00
}
// 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) {
2013-11-06 09:53:45 +08:00
n, err := f.c.readAt(f.handle, uint64(off), b)
return int(n), err
2013-11-06 09:42:14 +08:00
}
// Stat returns the FileInfo structure describing file. If there is an
// error, it will be of type *PathError.
func (f *File) Stat() (os.FileInfo, error) {
2013-11-06 09:53:45 +08:00
fi, err := f.c.fstat(f.handle)
if err == nil {
2013-11-06 13:03:08 +08:00
fi.name = path.Base(f.path)
2013-11-06 09:53:45 +08:00
}
return fi, err
2013-11-06 09:42:14 +08:00
}
2013-11-06 10:04:40 +08:00
// 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
}
2013-11-06 09:42:14 +08:00
// 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 {
2013-11-06 09:53:45 +08:00
c *Client
cur item
stack []item
descend bool
2013-11-06 09:42:14 +08:00
}
// 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 {
2013-11-06 09:53:45 +08:00
return w.cur.err
2013-11-06 09:42:14 +08:00
}
// 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 {
2013-11-06 09:53:45 +08:00
return w.cur.path
2013-11-06 09:42:14 +08:00
}
// Stat returns info for the most recent file or directory
// visited by a call to Step.
func (w *Walker) Stat() os.FileInfo {
2013-11-06 09:53:45 +08:00
return w.cur.info
2013-11-06 09:42:14 +08:00
}
// 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 {
2013-11-06 09:53:45 +08:00
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})
}
}
}
2013-11-06 09:42:14 +08:00
2013-11-06 09:53:45 +08:00
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
2013-11-06 09:42:14 +08:00
}
// SkipDir causes the currently visited directory to be skipped.
// If w is not on a directory, SkipDir has no effect.
func (w *Walker) SkipDir() {
2013-11-06 09:53:45 +08:00
w.descend = false
2013-11-06 09:42:14 +08:00
}
type item struct {
2013-11-06 09:53:45 +08:00
path string
info os.FileInfo
err error
2013-11-06 09:42:14 +08:00
}
2013-11-06 11:08:26 +08:00
// okOrErr returns nil if Err.Code is SSH_FX_OK, otherwise it returns the error.
2013-11-06 11:15:26 +08:00
func okOrErr(err error) error {
if err, ok := err.(*StatusError); ok && err.Code == SSH_FX_OK {
2013-11-06 11:08:26 +08:00
return nil
}
return err
}
2013-11-06 11:15:26 +08:00
2013-11-06 12:00:04 +08:00
func eofOrErr(err error) error {
if err, ok := err.(*StatusError); ok && err.Code == SSH_FX_EOF {
return io.EOF
}
return err
}
2013-11-06 11:15:26 +08:00
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,
}
}