sftpfs.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. package vfs
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/eikenb/pipeat"
  16. "github.com/pkg/sftp"
  17. "github.com/rs/xid"
  18. "golang.org/x/crypto/ssh"
  19. "github.com/drakkan/sftpgo/v2/kms"
  20. "github.com/drakkan/sftpgo/v2/logger"
  21. "github.com/drakkan/sftpgo/v2/sdk"
  22. "github.com/drakkan/sftpgo/v2/util"
  23. "github.com/drakkan/sftpgo/v2/version"
  24. )
  25. const (
  26. // sftpFsName is the name for the SFTP Fs implementation
  27. sftpFsName = "sftpfs"
  28. )
  29. // ErrSFTPLoop defines the error to return if an SFTP loop is detected
  30. var ErrSFTPLoop = errors.New("SFTP loop or nested local SFTP folders detected")
  31. // SFTPFsConfig defines the configuration for SFTP based filesystem
  32. type SFTPFsConfig struct {
  33. sdk.SFTPFsConfig
  34. forbiddenSelfUsernames []string `json:"-"`
  35. }
  36. func (c *SFTPFsConfig) isEqual(other *SFTPFsConfig) bool {
  37. if c.Endpoint != other.Endpoint {
  38. return false
  39. }
  40. if c.Username != other.Username {
  41. return false
  42. }
  43. if c.Prefix != other.Prefix {
  44. return false
  45. }
  46. if c.DisableCouncurrentReads != other.DisableCouncurrentReads {
  47. return false
  48. }
  49. if c.BufferSize != other.BufferSize {
  50. return false
  51. }
  52. if len(c.Fingerprints) != len(other.Fingerprints) {
  53. return false
  54. }
  55. for _, fp := range c.Fingerprints {
  56. if !util.IsStringInSlice(fp, other.Fingerprints) {
  57. return false
  58. }
  59. }
  60. c.setEmptyCredentialsIfNil()
  61. other.setEmptyCredentialsIfNil()
  62. if !c.Password.IsEqual(other.Password) {
  63. return false
  64. }
  65. return c.PrivateKey.IsEqual(other.PrivateKey)
  66. }
  67. func (c *SFTPFsConfig) setEmptyCredentialsIfNil() {
  68. if c.Password == nil {
  69. c.Password = kms.NewEmptySecret()
  70. }
  71. if c.PrivateKey == nil {
  72. c.PrivateKey = kms.NewEmptySecret()
  73. }
  74. }
  75. // Validate returns an error if the configuration is not valid
  76. func (c *SFTPFsConfig) Validate() error {
  77. c.setEmptyCredentialsIfNil()
  78. if c.Endpoint == "" {
  79. return errors.New("endpoint cannot be empty")
  80. }
  81. _, _, err := net.SplitHostPort(c.Endpoint)
  82. if err != nil {
  83. return fmt.Errorf("invalid endpoint: %v", err)
  84. }
  85. if c.Username == "" {
  86. return errors.New("username cannot be empty")
  87. }
  88. if c.BufferSize < 0 || c.BufferSize > 16 {
  89. return errors.New("invalid buffer_size, valid range is 0-16")
  90. }
  91. if err := c.validateCredentials(); err != nil {
  92. return err
  93. }
  94. if c.Prefix != "" {
  95. c.Prefix = util.CleanPath(c.Prefix)
  96. } else {
  97. c.Prefix = "/"
  98. }
  99. return nil
  100. }
  101. func (c *SFTPFsConfig) validateCredentials() error {
  102. if c.Password.IsEmpty() && c.PrivateKey.IsEmpty() {
  103. return errors.New("credentials cannot be empty")
  104. }
  105. if c.Password.IsEncrypted() && !c.Password.IsValid() {
  106. return errors.New("invalid encrypted password")
  107. }
  108. if !c.Password.IsEmpty() && !c.Password.IsValidInput() {
  109. return errors.New("invalid password")
  110. }
  111. if c.PrivateKey.IsEncrypted() && !c.PrivateKey.IsValid() {
  112. return errors.New("invalid encrypted private key")
  113. }
  114. if !c.PrivateKey.IsEmpty() && !c.PrivateKey.IsValidInput() {
  115. return errors.New("invalid private key")
  116. }
  117. return nil
  118. }
  119. // EncryptCredentials encrypts password and/or private key if they are in plain text
  120. func (c *SFTPFsConfig) EncryptCredentials(additionalData string) error {
  121. if c.Password.IsPlain() {
  122. c.Password.SetAdditionalData(additionalData)
  123. if err := c.Password.Encrypt(); err != nil {
  124. return err
  125. }
  126. }
  127. if c.PrivateKey.IsPlain() {
  128. c.PrivateKey.SetAdditionalData(additionalData)
  129. if err := c.PrivateKey.Encrypt(); err != nil {
  130. return err
  131. }
  132. }
  133. return nil
  134. }
  135. // SFTPFs is a Fs implementation for SFTP backends
  136. type SFTPFs struct {
  137. sync.Mutex
  138. connectionID string
  139. // if not empty this fs is mouted as virtual folder in the specified path
  140. mountPath string
  141. localTempDir string
  142. config *SFTPFsConfig
  143. sshClient *ssh.Client
  144. sftpClient *sftp.Client
  145. err chan error
  146. }
  147. // NewSFTPFs returns an SFTPFs object that allows to interact with an SFTP server
  148. func NewSFTPFs(connectionID, mountPath, localTempDir string, forbiddenSelfUsernames []string, config SFTPFsConfig) (Fs, error) {
  149. if localTempDir == "" {
  150. if tempPath != "" {
  151. localTempDir = tempPath
  152. } else {
  153. localTempDir = filepath.Clean(os.TempDir())
  154. }
  155. }
  156. if err := config.Validate(); err != nil {
  157. return nil, err
  158. }
  159. if !config.Password.IsEmpty() {
  160. if err := config.Password.TryDecrypt(); err != nil {
  161. return nil, err
  162. }
  163. }
  164. if !config.PrivateKey.IsEmpty() {
  165. if err := config.PrivateKey.TryDecrypt(); err != nil {
  166. return nil, err
  167. }
  168. }
  169. config.forbiddenSelfUsernames = forbiddenSelfUsernames
  170. sftpFs := &SFTPFs{
  171. connectionID: connectionID,
  172. mountPath: mountPath,
  173. localTempDir: localTempDir,
  174. config: &config,
  175. err: make(chan error, 1),
  176. }
  177. err := sftpFs.createConnection()
  178. return sftpFs, err
  179. }
  180. // Name returns the name for the Fs implementation
  181. func (fs *SFTPFs) Name() string {
  182. return fmt.Sprintf("%v %#v", sftpFsName, fs.config.Endpoint)
  183. }
  184. // ConnectionID returns the connection ID associated to this Fs implementation
  185. func (fs *SFTPFs) ConnectionID() string {
  186. return fs.connectionID
  187. }
  188. // Stat returns a FileInfo describing the named file
  189. func (fs *SFTPFs) Stat(name string) (os.FileInfo, error) {
  190. if err := fs.checkConnection(); err != nil {
  191. return nil, err
  192. }
  193. return fs.sftpClient.Stat(name)
  194. }
  195. // Lstat returns a FileInfo describing the named file
  196. func (fs *SFTPFs) Lstat(name string) (os.FileInfo, error) {
  197. if err := fs.checkConnection(); err != nil {
  198. return nil, err
  199. }
  200. return fs.sftpClient.Lstat(name)
  201. }
  202. // Open opens the named file for reading
  203. func (fs *SFTPFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  204. if err := fs.checkConnection(); err != nil {
  205. return nil, nil, nil, err
  206. }
  207. f, err := fs.sftpClient.Open(name)
  208. if err != nil {
  209. return nil, nil, nil, err
  210. }
  211. if fs.config.BufferSize == 0 {
  212. return f, nil, nil, err
  213. }
  214. if offset > 0 {
  215. _, err = f.Seek(offset, io.SeekStart)
  216. if err != nil {
  217. f.Close()
  218. return nil, nil, nil, err
  219. }
  220. }
  221. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  222. if err != nil {
  223. f.Close()
  224. return nil, nil, nil, err
  225. }
  226. go func() {
  227. // if we enable buffering the client stalls
  228. //br := bufio.NewReaderSize(f, int(fs.config.BufferSize)*1024*1024)
  229. //n, err := fs.copy(w, br)
  230. n, err := io.Copy(w, f)
  231. w.CloseWithError(err) //nolint:errcheck
  232. f.Close()
  233. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %v", name, n, err)
  234. }()
  235. return nil, r, nil, nil
  236. }
  237. // Create creates or opens the named file for writing
  238. func (fs *SFTPFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  239. err := fs.checkConnection()
  240. if err != nil {
  241. return nil, nil, nil, err
  242. }
  243. if fs.config.BufferSize == 0 {
  244. var f File
  245. if flag == 0 {
  246. f, err = fs.sftpClient.Create(name)
  247. } else {
  248. f, err = fs.sftpClient.OpenFile(name, flag)
  249. }
  250. return f, nil, nil, err
  251. }
  252. // buffering is enabled
  253. f, err := fs.sftpClient.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
  254. if err != nil {
  255. return nil, nil, nil, err
  256. }
  257. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  258. if err != nil {
  259. f.Close()
  260. return nil, nil, nil, err
  261. }
  262. p := NewPipeWriter(w)
  263. go func() {
  264. bw := bufio.NewWriterSize(f, int(fs.config.BufferSize)*1024*1024)
  265. // we don't use io.Copy since bufio.Writer implements io.WriterTo and
  266. // so it calls the sftp.File WriteTo method without buffering
  267. n, err := fs.copy(bw, r)
  268. errFlush := bw.Flush()
  269. if err == nil && errFlush != nil {
  270. err = errFlush
  271. }
  272. var errTruncate error
  273. if err != nil {
  274. errTruncate = f.Truncate(n)
  275. }
  276. errClose := f.Close()
  277. if err == nil && errClose != nil {
  278. err = errClose
  279. }
  280. r.CloseWithError(err) //nolint:errcheck
  281. p.Done(err)
  282. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, readed bytes: %v, err: %v err truncate: %v",
  283. name, n, err, errTruncate)
  284. }()
  285. return nil, p, nil, nil
  286. }
  287. // Rename renames (moves) source to target.
  288. func (fs *SFTPFs) Rename(source, target string) error {
  289. if err := fs.checkConnection(); err != nil {
  290. return err
  291. }
  292. return fs.sftpClient.Rename(source, target)
  293. }
  294. // Remove removes the named file or (empty) directory.
  295. func (fs *SFTPFs) Remove(name string, isDir bool) error {
  296. if err := fs.checkConnection(); err != nil {
  297. return err
  298. }
  299. return fs.sftpClient.Remove(name)
  300. }
  301. // Mkdir creates a new directory with the specified name and default permissions
  302. func (fs *SFTPFs) Mkdir(name string) error {
  303. if err := fs.checkConnection(); err != nil {
  304. return err
  305. }
  306. return fs.sftpClient.Mkdir(name)
  307. }
  308. // MkdirAll creates a directory named path, along with any necessary parents,
  309. // and returns nil, or else returns an error.
  310. // If path is already a directory, MkdirAll does nothing and returns nil.
  311. func (fs *SFTPFs) MkdirAll(name string, uid int, gid int) error {
  312. if err := fs.checkConnection(); err != nil {
  313. return err
  314. }
  315. return fs.sftpClient.MkdirAll(name)
  316. }
  317. // Symlink creates source as a symbolic link to target.
  318. func (fs *SFTPFs) Symlink(source, target string) error {
  319. if err := fs.checkConnection(); err != nil {
  320. return err
  321. }
  322. return fs.sftpClient.Symlink(source, target)
  323. }
  324. // Readlink returns the destination of the named symbolic link
  325. func (fs *SFTPFs) Readlink(name string) (string, error) {
  326. if err := fs.checkConnection(); err != nil {
  327. return "", err
  328. }
  329. return fs.sftpClient.ReadLink(name)
  330. }
  331. // Chown changes the numeric uid and gid of the named file.
  332. func (fs *SFTPFs) Chown(name string, uid int, gid int) error {
  333. if err := fs.checkConnection(); err != nil {
  334. return err
  335. }
  336. return fs.sftpClient.Chown(name, uid, gid)
  337. }
  338. // Chmod changes the mode of the named file to mode.
  339. func (fs *SFTPFs) Chmod(name string, mode os.FileMode) error {
  340. if err := fs.checkConnection(); err != nil {
  341. return err
  342. }
  343. return fs.sftpClient.Chmod(name, mode)
  344. }
  345. // Chtimes changes the access and modification times of the named file.
  346. func (fs *SFTPFs) Chtimes(name string, atime, mtime time.Time) error {
  347. if err := fs.checkConnection(); err != nil {
  348. return err
  349. }
  350. return fs.sftpClient.Chtimes(name, atime, mtime)
  351. }
  352. // Truncate changes the size of the named file.
  353. func (fs *SFTPFs) Truncate(name string, size int64) error {
  354. if err := fs.checkConnection(); err != nil {
  355. return err
  356. }
  357. return fs.sftpClient.Truncate(name, size)
  358. }
  359. // ReadDir reads the directory named by dirname and returns
  360. // a list of directory entries.
  361. func (fs *SFTPFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  362. if err := fs.checkConnection(); err != nil {
  363. return nil, err
  364. }
  365. return fs.sftpClient.ReadDir(dirname)
  366. }
  367. // IsUploadResumeSupported returns true if resuming uploads is supported.
  368. func (fs *SFTPFs) IsUploadResumeSupported() bool {
  369. return fs.config.BufferSize == 0
  370. }
  371. // IsAtomicUploadSupported returns true if atomic upload is supported.
  372. func (fs *SFTPFs) IsAtomicUploadSupported() bool {
  373. return fs.config.BufferSize == 0
  374. }
  375. // IsNotExist returns a boolean indicating whether the error is known to
  376. // report that a file or directory does not exist
  377. func (*SFTPFs) IsNotExist(err error) bool {
  378. return os.IsNotExist(err)
  379. }
  380. // IsPermission returns a boolean indicating whether the error is known to
  381. // report that permission is denied.
  382. func (*SFTPFs) IsPermission(err error) bool {
  383. return os.IsPermission(err)
  384. }
  385. // IsNotSupported returns true if the error indicate an unsupported operation
  386. func (*SFTPFs) IsNotSupported(err error) bool {
  387. if err == nil {
  388. return false
  389. }
  390. return err == ErrVfsUnsupported
  391. }
  392. // CheckRootPath creates the specified local root directory if it does not exists
  393. func (fs *SFTPFs) CheckRootPath(username string, uid int, gid int) bool {
  394. if fs.config.BufferSize > 0 {
  395. // we need a local directory for temporary files
  396. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  397. osFs.CheckRootPath(username, uid, gid)
  398. }
  399. if fs.config.Prefix == "/" {
  400. return true
  401. }
  402. if err := fs.MkdirAll(fs.config.Prefix, uid, gid); err != nil {
  403. fsLog(fs, logger.LevelDebug, "error creating root directory %#v for user %#v: %v", fs.config.Prefix, username, err)
  404. return false
  405. }
  406. return true
  407. }
  408. // ScanRootDirContents returns the number of files contained in a directory and
  409. // their size
  410. func (fs *SFTPFs) ScanRootDirContents() (int, int64, error) {
  411. return fs.GetDirSize(fs.config.Prefix)
  412. }
  413. // GetAtomicUploadPath returns the path to use for an atomic upload
  414. func (*SFTPFs) GetAtomicUploadPath(name string) string {
  415. dir := path.Dir(name)
  416. guid := xid.New().String()
  417. return path.Join(dir, ".sftpgo-upload."+guid+"."+path.Base(name))
  418. }
  419. // GetRelativePath returns the path for a file relative to the sftp prefix if any.
  420. // This is the path as seen by SFTPGo users
  421. func (fs *SFTPFs) GetRelativePath(name string) string {
  422. rel := path.Clean(name)
  423. if rel == "." {
  424. rel = ""
  425. }
  426. if !path.IsAbs(rel) {
  427. return "/" + rel
  428. }
  429. if fs.config.Prefix != "/" {
  430. if !strings.HasPrefix(rel, fs.config.Prefix) {
  431. rel = "/"
  432. }
  433. rel = path.Clean("/" + strings.TrimPrefix(rel, fs.config.Prefix))
  434. }
  435. if fs.mountPath != "" {
  436. rel = path.Join(fs.mountPath, rel)
  437. }
  438. return rel
  439. }
  440. // Walk walks the file tree rooted at root, calling walkFn for each file or
  441. // directory in the tree, including root
  442. func (fs *SFTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
  443. if err := fs.checkConnection(); err != nil {
  444. return err
  445. }
  446. walker := fs.sftpClient.Walk(root)
  447. for walker.Step() {
  448. err := walker.Err()
  449. if err != nil {
  450. return err
  451. }
  452. err = walkFn(walker.Path(), walker.Stat(), err)
  453. if err != nil {
  454. return err
  455. }
  456. }
  457. return nil
  458. }
  459. // Join joins any number of path elements into a single path
  460. func (*SFTPFs) Join(elem ...string) string {
  461. return path.Join(elem...)
  462. }
  463. // HasVirtualFolders returns true if folders are emulated
  464. func (*SFTPFs) HasVirtualFolders() bool {
  465. return false
  466. }
  467. // ResolvePath returns the matching filesystem path for the specified virtual path
  468. func (fs *SFTPFs) ResolvePath(virtualPath string) (string, error) {
  469. if fs.mountPath != "" {
  470. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  471. }
  472. if !path.IsAbs(virtualPath) {
  473. virtualPath = path.Clean("/" + virtualPath)
  474. }
  475. fsPath := fs.Join(fs.config.Prefix, virtualPath)
  476. if fs.config.Prefix != "/" && fsPath != "/" {
  477. // we need to check if this path is a symlink outside the given prefix
  478. // or a file/dir inside a dir symlinked outside the prefix
  479. if err := fs.checkConnection(); err != nil {
  480. return "", err
  481. }
  482. var validatedPath string
  483. var err error
  484. validatedPath, err = fs.getRealPath(fsPath)
  485. if err != nil && !os.IsNotExist(err) {
  486. fsLog(fs, logger.LevelWarn, "Invalid path resolution, original path %v resolved %#v err: %v",
  487. virtualPath, fsPath, err)
  488. return "", err
  489. } else if os.IsNotExist(err) {
  490. for os.IsNotExist(err) {
  491. validatedPath = path.Dir(validatedPath)
  492. if validatedPath == "/" {
  493. err = nil
  494. break
  495. }
  496. validatedPath, err = fs.getRealPath(validatedPath)
  497. }
  498. if err != nil {
  499. fsLog(fs, logger.LevelWarn, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  500. validatedPath, virtualPath, fsPath, err)
  501. return "", err
  502. }
  503. }
  504. if err := fs.isSubDir(validatedPath); err != nil {
  505. fsLog(fs, logger.LevelWarn, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  506. validatedPath, virtualPath, fsPath, err)
  507. return "", err
  508. }
  509. }
  510. return fsPath, nil
  511. }
  512. // getRealPath returns the real remote path trying to resolve symbolic links if any
  513. func (fs *SFTPFs) getRealPath(name string) (string, error) {
  514. info, err := fs.sftpClient.Lstat(name)
  515. if err != nil {
  516. return name, err
  517. }
  518. if info.Mode()&os.ModeSymlink != 0 {
  519. return fs.sftpClient.ReadLink(name)
  520. }
  521. return name, err
  522. }
  523. func (fs *SFTPFs) isSubDir(name string) error {
  524. if name == fs.config.Prefix {
  525. return nil
  526. }
  527. if len(name) < len(fs.config.Prefix) {
  528. err := fmt.Errorf("path %#v is not inside: %#v", name, fs.config.Prefix)
  529. return err
  530. }
  531. if !strings.HasPrefix(name, fs.config.Prefix+"/") {
  532. err := fmt.Errorf("path %#v is not inside: %#v", name, fs.config.Prefix)
  533. return err
  534. }
  535. return nil
  536. }
  537. // GetDirSize returns the number of files and the size for a folder
  538. // including any subfolders
  539. func (fs *SFTPFs) GetDirSize(dirname string) (int, int64, error) {
  540. numFiles := 0
  541. size := int64(0)
  542. if err := fs.checkConnection(); err != nil {
  543. return numFiles, size, err
  544. }
  545. isDir, err := IsDirectory(fs, dirname)
  546. if err == nil && isDir {
  547. walker := fs.sftpClient.Walk(dirname)
  548. for walker.Step() {
  549. err := walker.Err()
  550. if err != nil {
  551. return numFiles, size, err
  552. }
  553. if walker.Stat().Mode().IsRegular() {
  554. size += walker.Stat().Size()
  555. numFiles++
  556. }
  557. }
  558. }
  559. return numFiles, size, err
  560. }
  561. // GetMimeType returns the content type
  562. func (fs *SFTPFs) GetMimeType(name string) (string, error) {
  563. if err := fs.checkConnection(); err != nil {
  564. return "", err
  565. }
  566. f, err := fs.sftpClient.OpenFile(name, os.O_RDONLY)
  567. if err != nil {
  568. return "", err
  569. }
  570. defer f.Close()
  571. var buf [512]byte
  572. n, err := io.ReadFull(f, buf[:])
  573. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  574. return "", err
  575. }
  576. ctype := http.DetectContentType(buf[:n])
  577. // Rewind file.
  578. _, err = f.Seek(0, io.SeekStart)
  579. return ctype, err
  580. }
  581. // GetAvailableDiskSize return the available size for the specified path
  582. func (fs *SFTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  583. if err := fs.checkConnection(); err != nil {
  584. return nil, err
  585. }
  586. if _, ok := fs.sftpClient.HasExtension("[email protected]"); !ok {
  587. return nil, ErrStorageSizeUnavailable
  588. }
  589. return fs.sftpClient.StatVFS(dirName)
  590. }
  591. // Close the connection
  592. func (fs *SFTPFs) Close() error {
  593. fs.Lock()
  594. defer fs.Unlock()
  595. var sftpErr, sshErr error
  596. if fs.sftpClient != nil {
  597. sftpErr = fs.sftpClient.Close()
  598. }
  599. if fs.sshClient != nil {
  600. sshErr = fs.sshClient.Close()
  601. }
  602. if sftpErr != nil {
  603. return sftpErr
  604. }
  605. return sshErr
  606. }
  607. func (fs *SFTPFs) copy(dst io.Writer, src io.Reader) (written int64, err error) {
  608. buf := make([]byte, 32768)
  609. for {
  610. nr, er := src.Read(buf)
  611. if nr > 0 {
  612. nw, ew := dst.Write(buf[0:nr])
  613. if nw < 0 || nr < nw {
  614. nw = 0
  615. if ew == nil {
  616. ew = errors.New("invalid write")
  617. }
  618. }
  619. written += int64(nw)
  620. if ew != nil {
  621. err = ew
  622. break
  623. }
  624. if nr != nw {
  625. err = io.ErrShortWrite
  626. break
  627. }
  628. }
  629. if er != nil {
  630. if er != io.EOF {
  631. err = er
  632. }
  633. break
  634. }
  635. }
  636. return written, err
  637. }
  638. func (fs *SFTPFs) checkConnection() error {
  639. err := fs.closed()
  640. if err == nil {
  641. return nil
  642. }
  643. return fs.createConnection()
  644. }
  645. func (fs *SFTPFs) createConnection() error {
  646. fs.Lock()
  647. defer fs.Unlock()
  648. var err error
  649. clientConfig := &ssh.ClientConfig{
  650. User: fs.config.Username,
  651. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  652. fp := ssh.FingerprintSHA256(key)
  653. if util.IsStringInSlice(fp, sftpFingerprints) {
  654. if util.IsStringInSlice(fs.config.Username, fs.config.forbiddenSelfUsernames) {
  655. fsLog(fs, logger.LevelWarn, "SFTP loop or nested local SFTP folders detected, mount path %#v, username %#v, forbidden usernames: %+v",
  656. fs.mountPath, fs.config.Username, fs.config.forbiddenSelfUsernames)
  657. return ErrSFTPLoop
  658. }
  659. }
  660. if len(fs.config.Fingerprints) > 0 {
  661. for _, provided := range fs.config.Fingerprints {
  662. if provided == fp {
  663. return nil
  664. }
  665. }
  666. return fmt.Errorf("invalid fingerprint %#v", fp)
  667. }
  668. fsLog(fs, logger.LevelWarn, "login without host key validation, please provide at least a fingerprint!")
  669. return nil
  670. },
  671. ClientVersion: fmt.Sprintf("SSH-2.0-SFTPGo_%v", version.Get().Version),
  672. }
  673. if fs.config.PrivateKey.GetPayload() != "" {
  674. signer, err := ssh.ParsePrivateKey([]byte(fs.config.PrivateKey.GetPayload()))
  675. if err != nil {
  676. fs.err <- err
  677. return err
  678. }
  679. clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
  680. }
  681. if fs.config.Password.GetPayload() != "" {
  682. clientConfig.Auth = append(clientConfig.Auth, ssh.Password(fs.config.Password.GetPayload()))
  683. }
  684. fs.sshClient, err = ssh.Dial("tcp", fs.config.Endpoint, clientConfig)
  685. if err != nil {
  686. fs.err <- err
  687. return err
  688. }
  689. fs.sftpClient, err = sftp.NewClient(fs.sshClient)
  690. if err != nil {
  691. fs.sshClient.Close()
  692. fs.err <- err
  693. return err
  694. }
  695. if fs.config.DisableCouncurrentReads {
  696. fsLog(fs, logger.LevelDebug, "disabling concurrent reads")
  697. opt := sftp.UseConcurrentReads(false)
  698. opt(fs.sftpClient) //nolint:errcheck
  699. }
  700. if fs.config.BufferSize > 0 {
  701. fsLog(fs, logger.LevelDebug, "enabling concurrent writes")
  702. opt := sftp.UseConcurrentWrites(true)
  703. opt(fs.sftpClient) //nolint:errcheck
  704. }
  705. go fs.wait()
  706. return nil
  707. }
  708. func (fs *SFTPFs) wait() {
  709. // we wait on the sftp client otherwise if the channel is closed but not the connection
  710. // we don't detect the event.
  711. fs.err <- fs.sftpClient.Wait()
  712. fsLog(fs, logger.LevelDebug, "sftp channel closed")
  713. fs.Lock()
  714. defer fs.Unlock()
  715. if fs.sshClient != nil {
  716. fs.sshClient.Close()
  717. }
  718. }
  719. func (fs *SFTPFs) closed() error {
  720. select {
  721. case err := <-fs.err:
  722. return err
  723. default:
  724. return nil
  725. }
  726. }