sftp.go 10.7 KB
Newer Older
D
Davies Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
// Part of this file is borrowed from Rclone under MIT license:
// https://github.com/ncw/rclone/blob/master/backend/sftp/sftp.go

package object

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"os"
	"path/filepath"
C
chnliyong 已提交
14
	"runtime"
D
Davies Liu 已提交
15
	"sort"
D
Davies Liu 已提交
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
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
)

// conn encapsulates an ssh client and corresponding sftp client
type conn struct {
	sshClient  *ssh.Client
	sftpClient *sftp.Client
	err        chan error
}

// Wait for connection to close
func (c *conn) wait() {
	c.err <- c.sshClient.Conn.Wait()
}

// Closes the connection
func (c *conn) close() error {
	sftpErr := c.sftpClient.Close()
	sshErr := c.sshClient.Close()
	if sftpErr != nil {
		return sftpErr
	}
	return sshErr
}

// Returns an error if closed
func (c *conn) closed() error {
	select {
	case err := <-c.err:
		return err
	default:
	}
	return nil
}

type sftpStore struct {
D
Davies Liu 已提交
58
	DefaultObjectStorage
D
Davies Liu 已提交
59
	host   string
60
	port   string
D
Davies Liu 已提交
61 62 63 64
	root   string
	config *ssh.ClientConfig
	poolMu sync.Mutex
	pool   []*conn
D
Davies Liu 已提交
65 66 67 68 69 70 71
}

// Open a new connection to the SFTP server.
func (f *sftpStore) sftpConnection() (c *conn, err error) {
	c = &conn{
		err: make(chan error, 1),
	}
72
	conn, err := net.Dial("tcp", net.JoinHostPort(f.host, f.port))
D
Davies Liu 已提交
73 74 75
	if err != nil {
		return nil, err
	}
76
	sshc, chans, reqs, err := ssh.NewClientConn(conn, net.JoinHostPort(f.host, f.port), f.config)
D
Davies Liu 已提交
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
	if err != nil {
		return nil, err
	}
	c.sshClient = ssh.NewClient(sshc, chans, reqs)
	c.sftpClient, err = sftp.NewClient(c.sshClient)
	if err != nil {
		_ = c.sshClient.Close()
		return nil, errors.Wrap(err, "couldn't initialise SFTP")
	}
	go c.wait()
	return c, nil
}

// Get an SFTP connection from the pool, or open a new one
func (f *sftpStore) getSftpConnection() (c *conn, err error) {
	f.poolMu.Lock()
	for len(f.pool) > 0 {
		c = f.pool[0]
		f.pool = f.pool[1:]
		err := c.closed()
		if err == nil {
			break
		}
		c = nil
	}
	f.poolMu.Unlock()
	if c != nil {
		return c, nil
	}
	return f.sftpConnection()
}

// Return an SFTP connection to the pool
//
// It nils the pointed to connection out so it can't be reused
//
// if err is not nil then it checks the connection is alive using a
// Getwd request
func (f *sftpStore) putSftpConnection(pc **conn, err error) {
	c := *pc
	*pc = nil
	if err != nil {
		// work out if this is an expected error
		underlyingErr := errors.Cause(err)
		isRegularError := false
		switch underlyingErr {
		case os.ErrNotExist:
			isRegularError = true
		default:
			switch underlyingErr.(type) {
			case *sftp.StatusError, *os.PathError:
				isRegularError = true
			}
		}
		// If not a regular SFTP error code then check the connection
		if !isRegularError {
			_, nopErr := c.sftpClient.Getwd()
			if nopErr != nil {
				_ = c.close()
				return
			}
		}
	}
	f.poolMu.Lock()
	f.pool = append(f.pool, c)
	f.poolMu.Unlock()
}

func (f *sftpStore) String() string {
	return fmt.Sprintf("%s@%s:%s", f.config.User, f.host, f.root)
}

149
// always preserve suffix `/` for directory key
D
Davies Liu 已提交
150
func (f *sftpStore) path(key string) string {
151 152 153
	if key == "" {
		return f.root
	}
C
chnliyong 已提交
154
	var absPath string
155
	if strings.HasSuffix(key, dirSuffix) {
C
chnliyong 已提交
156 157 158 159 160 161
		absPath = filepath.Join(f.root, key) + dirSuffix
	} else {
		absPath = filepath.Join(f.root, key)
	}
	if runtime.GOOS == "windows" {
		absPath = strings.Replace(absPath, "\\", "/", -1)
162
	}
C
chnliyong 已提交
163
	return absPath
D
Davies Liu 已提交
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
func (f *sftpStore) Head(key string) (*Object, error) {
	c, err := f.getSftpConnection()
	if err != nil {
		return nil, err
	}
	defer f.putSftpConnection(&c, err)

	info, err := c.sftpClient.Stat(f.path(key))
	if err != nil {
		return nil, err
	}

	objKey, size := key, info.Size()
	if info.IsDir() {
		objKey, size = key+"/", 0
	}
	return &Object{
		objKey,
		size,
		info.ModTime(),
		info.IsDir(),
	}, nil
}

D
Davies Liu 已提交
190 191 192 193 194 195 196 197 198 199 200 201
func (f *sftpStore) Get(key string, off, limit int64) (io.ReadCloser, error) {
	c, err := f.getSftpConnection()
	if err != nil {
		return nil, err
	}
	defer f.putSftpConnection(&c, err)

	p := f.path(key)
	ff, err := c.sftpClient.Open(p)
	if err != nil {
		return nil, err
	}
202 203 204 205 206 207 208 209
	finfo, err := ff.Stat()
	if err != nil {
		return nil, err
	}
	if finfo.IsDir() {
		return ioutil.NopCloser(bytes.NewBuffer([]byte{})), nil
	}

D
Davies Liu 已提交
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
	if off > 0 {
		if _, err := ff.Seek(off, 0); err != nil {
			ff.Close()
			return nil, err
		}
	}
	if limit > 0 {
		buf := make([]byte, limit)
		if n, err := ff.Read(buf); n == 0 && err != nil {
			return nil, err
		} else {
			return ioutil.NopCloser(bytes.NewBuffer(buf[:n])), nil
		}
	}
	return ff, err
}

func (f *sftpStore) Put(key string, in io.Reader) error {
	c, err := f.getSftpConnection()
	if err != nil {
		return err
	}
	defer f.putSftpConnection(&c, err)

	p := f.path(key)
D
Davies Liu 已提交
235 236 237
	if strings.HasSuffix(p, dirSuffix) {
		return c.sftpClient.MkdirAll(p)
	}
D
Davies Liu 已提交
238 239 240
	if err := c.sftpClient.MkdirAll(filepath.Dir(p)); err != nil {
		return err
	}
D
Davies Liu 已提交
241
	tmp := filepath.Join(filepath.Dir(p), "."+filepath.Base(p)+".tmp")
C
chnliyong 已提交
242 243 244
	if runtime.GOOS == "windows" {
		tmp = strings.Replace(tmp, "\\", "/", -1)
	}
D
Davies Liu 已提交
245 246

	ff, err := c.sftpClient.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC)
D
Davies Liu 已提交
247 248 249
	if err != nil {
		return err
	}
D
Davies Liu 已提交
250
	defer func() { _ = c.sftpClient.Remove(tmp) }()
251
	buf := bufPool.Get().(*[]byte)
252
	defer bufPool.Put(buf)
253
	_, err = io.CopyBuffer(ff, in, *buf)
D
Davies Liu 已提交
254 255 256
	if err != nil {
		ff.Close()
		return err
D
Davies Liu 已提交
257
	}
D
Davies Liu 已提交
258 259 260 261 262
	err = ff.Close()
	if err != nil {
		return err
	}
	return c.sftpClient.Rename(tmp, p)
D
Davies Liu 已提交
263 264
}

D
Davies Liu 已提交
265
func (f *sftpStore) Chtimes(key string, mtime time.Time) error {
266
	c, err := f.getSftpConnection()
D
Davies Liu 已提交
267 268 269
	if err != nil {
		return err
	}
270
	defer f.putSftpConnection(&c, err)
D
Davies Liu 已提交
271
	return c.sftpClient.Chtimes(f.path(key), mtime, mtime)
D
Davies Liu 已提交
272 273
}

D
Davies Liu 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
func (f *sftpStore) Chmod(path string, mode os.FileMode) error {
	c, err := f.getSftpConnection()
	if err != nil {
		return err
	}
	defer f.putSftpConnection(&c, err)
	return c.sftpClient.Chmod(path, mode)
}

func (f *sftpStore) Chown(path string, owner, group string) error {
	c, err := f.getSftpConnection()
	if err != nil {
		return err
	}
	defer f.putSftpConnection(&c, err)
	uid := lookupUser(owner)
	gid := lookupGroup(group)
	return c.sftpClient.Chown(path, uid, gid)
}

D
Davies Liu 已提交
294 295 296 297 298 299
func (f *sftpStore) Delete(key string) error {
	c, err := f.getSftpConnection()
	if err != nil {
		return err
	}
	defer f.putSftpConnection(&c, err)
D
Davies Liu 已提交
300 301 302 303 304
	err = c.sftpClient.Remove(f.path(key))
	if err != nil && os.IsNotExist(err) {
		err = nil
	}
	return err
D
Davies Liu 已提交
305 306
}

D
Davies Liu 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
type sortFI []os.FileInfo

func (s sortFI) Len() int      { return len(s) }
func (s sortFI) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortFI) Less(i, j int) bool {
	name1 := s[i].Name()
	if s[i].IsDir() {
		name1 += "/"
	}
	name2 := s[j].Name()
	if s[j].IsDir() {
		name2 += "/"
	}
	return name1 < name2
}

323
func (f *sftpStore) doFind(c *sftp.Client, path, marker string, out chan *Object) {
D
Davies Liu 已提交
324 325
	infos, err := c.ReadDir(path)
	if err != nil {
D
Davies Liu 已提交
326
		logger.Errorf("readdir %s: %s", path, err)
D
Davies Liu 已提交
327 328
		return
	}
329

D
Davies Liu 已提交
330 331
	sort.Sort(sortFI(infos))
	for _, fi := range infos {
332
		p := path + fi.Name()
D
Davies Liu 已提交
333
		key := p[len(f.root):]
334
		if key > marker {
D
Davies Liu 已提交
335
			if fi.IsDir() {
336 337 338
				out <- &Object{key + "/", 0, fi.ModTime(), true}
			} else {
				out <- &Object{key, fi.Size(), fi.ModTime(), false}
D
Davies Liu 已提交
339 340
			}
		}
341
		if fi.IsDir() && (key > marker || strings.HasPrefix(marker, key)) {
342
			f.doFind(c, p+dirSuffix, marker, out)
D
Davies Liu 已提交
343
		}
D
Davies Liu 已提交
344 345 346
	}
}

347
func (f *sftpStore) find(c *sftp.Client, path, marker string, out chan *Object) {
348 349 350 351 352 353
	if strings.HasSuffix(path, dirSuffix) {
		fi, err := c.Stat(path)
		if err != nil {
			logger.Errorf("Stat %s error: %q", path, err)
			return
		}
354 355 356
		if marker == "" {
			out <- &Object{"", 0, fi.ModTime(), true}
		}
357 358
		f.doFind(c, path, marker, out)
	} else {
359 360
		// As files or dirs in the same directory of file `path` resides
		// may have prefix `path`, we should list the directory.
361
		dir := filepath.Dir(path) + dirSuffix
362 363 364 365 366 367 368 369
		infos, err := c.ReadDir(dir)
		if err != nil {
			logger.Errorf("readdir %s: %s", dir, err)
			return
		}

		sort.Sort(sortFI(infos))
		for _, fi := range infos {
370
			p := dir + fi.Name()
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
			if !strings.HasPrefix(p, f.root) {
				if p > f.root {
					break
				}
				continue
			}

			key := p[len(f.root):]
			if key > marker || marker == "" {
				if fi.IsDir() {
					out <- &Object{key + "/", 0, fi.ModTime(), true}
				} else {
					out <- &Object{key, fi.Size(), fi.ModTime(), false}
				}
			}
			if fi.IsDir() && (key > marker || strings.HasPrefix(marker, key)) {
387
				f.doFind(c, p+dirSuffix, marker, out)
388 389
			}
		}
390 391 392
	}
}

D
Davies Liu 已提交
393
func (f *sftpStore) List(prefix, marker string, limit int64) ([]*Object, error) {
D
Davies Liu 已提交
394 395 396 397 398 399 400
	return nil, notSupported
}

func (f *sftpStore) ListAll(prefix, marker string) (<-chan *Object, error) {
	c, err := f.getSftpConnection()
	if err != nil {
		return nil, err
D
Davies Liu 已提交
401
	}
D
Davies Liu 已提交
402 403 404
	listed := make(chan *Object, 10240)
	go func() {
		defer f.putSftpConnection(&c, nil)
405 406

		f.find(c.sftpClient, f.path(prefix), marker, listed)
D
Davies Liu 已提交
407 408 409
		close(listed)
	}()
	return listed, nil
D
Davies Liu 已提交
410 411
}

D
Davies Liu 已提交
412
func newSftp(endpoint, user, pass string) (ObjectStorage, error) {
C
chnliyong 已提交
413 414 415 416
	idx := strings.LastIndex(endpoint, ":")
	host, port, err := net.SplitHostPort(endpoint[:idx])
	if err != nil && strings.Contains(err.Error(), "missing port") {
		host, port, err = net.SplitHostPort(endpoint[:idx] + ":22")
417
	}
C
chnliyong 已提交
418 419 420 421
	if err != nil {
		return nil, fmt.Errorf("unable to parse host from endpoint (%s): %q", endpoint, err)
	}
	root := filepath.Clean(endpoint[idx+1:])
C
chnliyong 已提交
422 423 424
	if runtime.GOOS == "windows" {
		root = strings.Replace(root, "\\", "/", -1)
	}
425 426
	// append suffix `/` removed by filepath.Clean()
	// `.` is a directory, add `/`
C
chnliyong 已提交
427
	if strings.HasSuffix(endpoint[idx+1:], dirSuffix) || root == "." {
428 429
		root = root + dirSuffix
	}
430 431 432 433 434 435 436 437 438 439 440 441 442 443

	config := &ssh.ClientConfig{
		User:            user,
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		Timeout:         time.Second * 3,
	}

	if pass != "" {
		config.Auth = append(config.Auth, ssh.Password(pass))
	}

	if privateKeyPath := os.Getenv("SSH_PRIVATE_KEY_PATH"); privateKeyPath != "" {
		key, err := ioutil.ReadFile(privateKeyPath)
		if err != nil {
D
Davies Liu 已提交
444
			return nil, fmt.Errorf("unable to read private key, error: %v", err)
445 446 447 448
		}

		signer, err := ssh.ParsePrivateKey(key)
		if err != nil {
D
Davies Liu 已提交
449
			return nil, fmt.Errorf("unable to parse private key, error: %v", err)
450 451 452 453 454
		}

		config.Auth = append(config.Auth, ssh.PublicKeys(signer))
	}

455
	f := &sftpStore{
C
chnliyong 已提交
456
		host:   host,
457
		port:   port,
458 459
		root:   root,
		config: config,
D
Davies Liu 已提交
460
	}
461 462 463 464

	c, err := f.getSftpConnection()
	if err != nil {
		logger.Errorf("getSftpConnection failed: %s", err)
D
Davies Liu 已提交
465
		return nil, err
466 467 468 469 470 471
	}
	defer f.putSftpConnection(&c, err)

	if strings.HasSuffix(root, dirSuffix) {
		logger.Debugf("Ensure dicectory %s", root)
		if err := c.sftpClient.MkdirAll(root); err != nil {
D
Davies Liu 已提交
472
			return nil, fmt.Errorf("Creating directory %s failed: %q", root, err)
473 474 475 476 477
		}
	} else {
		dir := filepath.Dir(root)
		logger.Debugf("Ensure dicectory %s", dir)
		if err := c.sftpClient.MkdirAll(dir); err != nil {
D
Davies Liu 已提交
478
			return nil, fmt.Errorf("Creating directory %s failed: %q", dir, err)
479 480 481
		}
	}

D
Davies Liu 已提交
482
	return f, nil
D
Davies Liu 已提交
483 484 485
}

func init() {
D
Davies Liu 已提交
486
	Register("sftp", newSftp)
D
Davies Liu 已提交
487
}