sftpfs.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package vfs
  15. import (
  16. "bufio"
  17. "bytes"
  18. "errors"
  19. "fmt"
  20. "hash/fnv"
  21. "io"
  22. "io/fs"
  23. "net"
  24. "net/http"
  25. "os"
  26. "path"
  27. "path/filepath"
  28. "strconv"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "github.com/eikenb/pipeat"
  34. "github.com/pkg/sftp"
  35. "github.com/robfig/cron/v3"
  36. "github.com/rs/xid"
  37. "github.com/sftpgo/sdk"
  38. "golang.org/x/crypto/ssh"
  39. "github.com/drakkan/sftpgo/v2/internal/kms"
  40. "github.com/drakkan/sftpgo/v2/internal/logger"
  41. "github.com/drakkan/sftpgo/v2/internal/util"
  42. "github.com/drakkan/sftpgo/v2/internal/version"
  43. )
  44. const (
  45. // sftpFsName is the name for the SFTP Fs implementation
  46. sftpFsName = "sftpfs"
  47. logSenderSFTPCache = "sftpCache"
  48. maxSessionsPerConnection = 5
  49. )
  50. var (
  51. // ErrSFTPLoop defines the error to return if an SFTP loop is detected
  52. ErrSFTPLoop = errors.New("SFTP loop or nested local SFTP folders detected")
  53. sftpConnsCache = newSFTPConnectionCache()
  54. )
  55. // SFTPFsConfig defines the configuration for SFTP based filesystem
  56. type SFTPFsConfig struct {
  57. sdk.BaseSFTPFsConfig
  58. Password *kms.Secret `json:"password,omitempty"`
  59. PrivateKey *kms.Secret `json:"private_key,omitempty"`
  60. KeyPassphrase *kms.Secret `json:"key_passphrase,omitempty"`
  61. forbiddenSelfUsernames []string `json:"-"`
  62. }
  63. // HideConfidentialData hides confidential data
  64. func (c *SFTPFsConfig) HideConfidentialData() {
  65. if c.Password != nil {
  66. c.Password.Hide()
  67. }
  68. if c.PrivateKey != nil {
  69. c.PrivateKey.Hide()
  70. }
  71. if c.KeyPassphrase != nil {
  72. c.KeyPassphrase.Hide()
  73. }
  74. }
  75. func (c *SFTPFsConfig) setNilSecretsIfEmpty() {
  76. if c.Password != nil && c.Password.IsEmpty() {
  77. c.Password = nil
  78. }
  79. if c.PrivateKey != nil && c.PrivateKey.IsEmpty() {
  80. c.PrivateKey = nil
  81. }
  82. if c.KeyPassphrase != nil && c.KeyPassphrase.IsEmpty() {
  83. c.KeyPassphrase = nil
  84. }
  85. }
  86. func (c *SFTPFsConfig) isEqual(other SFTPFsConfig) bool {
  87. if c.Endpoint != other.Endpoint {
  88. return false
  89. }
  90. if c.Username != other.Username {
  91. return false
  92. }
  93. if c.Prefix != other.Prefix {
  94. return false
  95. }
  96. if c.DisableCouncurrentReads != other.DisableCouncurrentReads {
  97. return false
  98. }
  99. if c.BufferSize != other.BufferSize {
  100. return false
  101. }
  102. if len(c.Fingerprints) != len(other.Fingerprints) {
  103. return false
  104. }
  105. for _, fp := range c.Fingerprints {
  106. if !util.Contains(other.Fingerprints, fp) {
  107. return false
  108. }
  109. }
  110. c.setEmptyCredentialsIfNil()
  111. other.setEmptyCredentialsIfNil()
  112. if !c.Password.IsEqual(other.Password) {
  113. return false
  114. }
  115. if !c.KeyPassphrase.IsEqual(other.KeyPassphrase) {
  116. return false
  117. }
  118. return c.PrivateKey.IsEqual(other.PrivateKey)
  119. }
  120. func (c *SFTPFsConfig) setEmptyCredentialsIfNil() {
  121. if c.Password == nil {
  122. c.Password = kms.NewEmptySecret()
  123. }
  124. if c.PrivateKey == nil {
  125. c.PrivateKey = kms.NewEmptySecret()
  126. }
  127. if c.KeyPassphrase == nil {
  128. c.KeyPassphrase = kms.NewEmptySecret()
  129. }
  130. }
  131. func (c *SFTPFsConfig) isSameResource(other SFTPFsConfig) bool {
  132. if c.EqualityCheckMode > 0 || other.EqualityCheckMode > 0 {
  133. if c.Username != other.Username {
  134. return false
  135. }
  136. }
  137. return c.Endpoint == other.Endpoint
  138. }
  139. // validate returns an error if the configuration is not valid
  140. func (c *SFTPFsConfig) validate() error {
  141. c.setEmptyCredentialsIfNil()
  142. if c.Endpoint == "" {
  143. return errors.New("endpoint cannot be empty")
  144. }
  145. if !strings.Contains(c.Endpoint, ":") {
  146. c.Endpoint += ":22"
  147. }
  148. _, _, err := net.SplitHostPort(c.Endpoint)
  149. if err != nil {
  150. return fmt.Errorf("invalid endpoint: %v", err)
  151. }
  152. if c.Username == "" {
  153. return errors.New("username cannot be empty")
  154. }
  155. if c.BufferSize < 0 || c.BufferSize > 16 {
  156. return errors.New("invalid buffer_size, valid range is 0-16")
  157. }
  158. if !isEqualityCheckModeValid(c.EqualityCheckMode) {
  159. return errors.New("invalid equality_check_mode")
  160. }
  161. if err := c.validateCredentials(); err != nil {
  162. return err
  163. }
  164. if c.Prefix != "" {
  165. c.Prefix = util.CleanPath(c.Prefix)
  166. } else {
  167. c.Prefix = "/"
  168. }
  169. return nil
  170. }
  171. func (c *SFTPFsConfig) validateCredentials() error {
  172. if c.Password.IsEmpty() && c.PrivateKey.IsEmpty() {
  173. return errors.New("credentials cannot be empty")
  174. }
  175. if c.Password.IsEncrypted() && !c.Password.IsValid() {
  176. return errors.New("invalid encrypted password")
  177. }
  178. if !c.Password.IsEmpty() && !c.Password.IsValidInput() {
  179. return errors.New("invalid password")
  180. }
  181. if c.PrivateKey.IsEncrypted() && !c.PrivateKey.IsValid() {
  182. return errors.New("invalid encrypted private key")
  183. }
  184. if !c.PrivateKey.IsEmpty() && !c.PrivateKey.IsValidInput() {
  185. return errors.New("invalid private key")
  186. }
  187. if c.KeyPassphrase.IsEncrypted() && !c.KeyPassphrase.IsValid() {
  188. return errors.New("invalid encrypted private key passphrase")
  189. }
  190. if !c.KeyPassphrase.IsEmpty() && !c.KeyPassphrase.IsValidInput() {
  191. return errors.New("invalid private key passphrase")
  192. }
  193. return nil
  194. }
  195. // ValidateAndEncryptCredentials validates the config and encrypts credentials if they are in plain text
  196. func (c *SFTPFsConfig) ValidateAndEncryptCredentials(additionalData string) error {
  197. if err := c.validate(); err != nil {
  198. return util.NewValidationError(fmt.Sprintf("could not validate SFTP fs config: %v", err))
  199. }
  200. if c.Password.IsPlain() {
  201. c.Password.SetAdditionalData(additionalData)
  202. if err := c.Password.Encrypt(); err != nil {
  203. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs password: %v", err))
  204. }
  205. }
  206. if c.PrivateKey.IsPlain() {
  207. c.PrivateKey.SetAdditionalData(additionalData)
  208. if err := c.PrivateKey.Encrypt(); err != nil {
  209. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key: %v", err))
  210. }
  211. }
  212. if c.KeyPassphrase.IsPlain() {
  213. c.KeyPassphrase.SetAdditionalData(additionalData)
  214. if err := c.KeyPassphrase.Encrypt(); err != nil {
  215. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key passphrase: %v", err))
  216. }
  217. }
  218. return nil
  219. }
  220. // getUniqueID returns an hash of the settings used to connect to the SFTP server
  221. func (c *SFTPFsConfig) getUniqueID(partition int) uint64 {
  222. h := fnv.New64a()
  223. var b bytes.Buffer
  224. b.WriteString(c.Endpoint)
  225. b.WriteString(c.Username)
  226. b.WriteString(strings.Join(c.Fingerprints, ""))
  227. b.WriteString(strconv.FormatBool(c.DisableCouncurrentReads))
  228. b.WriteString(strconv.FormatInt(c.BufferSize, 10))
  229. b.WriteString(c.Password.GetPayload())
  230. b.WriteString(c.PrivateKey.GetPayload())
  231. b.WriteString(c.KeyPassphrase.GetPayload())
  232. if allowSelfConnections != 0 {
  233. b.WriteString(strings.Join(c.forbiddenSelfUsernames, ""))
  234. }
  235. b.WriteString(strconv.Itoa(partition))
  236. h.Write(b.Bytes())
  237. return h.Sum64()
  238. }
  239. // SFTPFs is a Fs implementation for SFTP backends
  240. type SFTPFs struct {
  241. connectionID string
  242. // if not empty this fs is mouted as virtual folder in the specified path
  243. mountPath string
  244. localTempDir string
  245. config *SFTPFsConfig
  246. conn *sftpConnection
  247. }
  248. // NewSFTPFs returns an SFTPFs object that allows to interact with an SFTP server
  249. func NewSFTPFs(connectionID, mountPath, localTempDir string, forbiddenSelfUsernames []string, config SFTPFsConfig) (Fs, error) {
  250. if localTempDir == "" {
  251. localTempDir = getLocalTempDir()
  252. }
  253. if err := config.validate(); err != nil {
  254. return nil, err
  255. }
  256. if !config.Password.IsEmpty() {
  257. if err := config.Password.TryDecrypt(); err != nil {
  258. return nil, err
  259. }
  260. }
  261. if !config.PrivateKey.IsEmpty() {
  262. if err := config.PrivateKey.TryDecrypt(); err != nil {
  263. return nil, err
  264. }
  265. }
  266. if !config.KeyPassphrase.IsEmpty() {
  267. if err := config.KeyPassphrase.TryDecrypt(); err != nil {
  268. return nil, err
  269. }
  270. }
  271. config.forbiddenSelfUsernames = forbiddenSelfUsernames
  272. sftpFs := &SFTPFs{
  273. connectionID: connectionID,
  274. mountPath: getMountPath(mountPath),
  275. localTempDir: localTempDir,
  276. config: &config,
  277. conn: sftpConnsCache.Get(&config, connectionID),
  278. }
  279. err := sftpFs.createConnection()
  280. if err != nil {
  281. sftpFs.Close() //nolint:errcheck
  282. }
  283. return sftpFs, err
  284. }
  285. // Name returns the name for the Fs implementation
  286. func (fs *SFTPFs) Name() string {
  287. return fmt.Sprintf(`%s %q@%q`, sftpFsName, fs.config.Username, fs.config.Endpoint)
  288. }
  289. // ConnectionID returns the connection ID associated to this Fs implementation
  290. func (fs *SFTPFs) ConnectionID() string {
  291. return fs.connectionID
  292. }
  293. // Stat returns a FileInfo describing the named file
  294. func (fs *SFTPFs) Stat(name string) (os.FileInfo, error) {
  295. client, err := fs.conn.getClient()
  296. if err != nil {
  297. return nil, err
  298. }
  299. return client.Stat(name)
  300. }
  301. // Lstat returns a FileInfo describing the named file
  302. func (fs *SFTPFs) Lstat(name string) (os.FileInfo, error) {
  303. client, err := fs.conn.getClient()
  304. if err != nil {
  305. return nil, err
  306. }
  307. return client.Lstat(name)
  308. }
  309. // Open opens the named file for reading
  310. func (fs *SFTPFs) Open(name string, offset int64) (File, *PipeReader, func(), error) {
  311. client, err := fs.conn.getClient()
  312. if err != nil {
  313. return nil, nil, nil, err
  314. }
  315. f, err := client.Open(name)
  316. if err != nil {
  317. return nil, nil, nil, err
  318. }
  319. if offset > 0 {
  320. _, err = f.Seek(offset, io.SeekStart)
  321. if err != nil {
  322. f.Close()
  323. return nil, nil, nil, err
  324. }
  325. }
  326. if fs.config.BufferSize == 0 {
  327. return f, nil, nil, nil
  328. }
  329. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  330. if err != nil {
  331. f.Close()
  332. return nil, nil, nil, err
  333. }
  334. p := NewPipeReader(r)
  335. go func() {
  336. // if we enable buffering the client stalls
  337. //br := bufio.NewReaderSize(f, int(fs.config.BufferSize)*1024*1024)
  338. //n, err := fs.copy(w, br)
  339. n, err := io.Copy(w, f)
  340. w.CloseWithError(err) //nolint:errcheck
  341. f.Close()
  342. fsLog(fs, logger.LevelDebug, "download completed, path: %q size: %v, err: %v", name, n, err)
  343. }()
  344. return nil, p, nil, nil
  345. }
  346. // Create creates or opens the named file for writing
  347. func (fs *SFTPFs) Create(name string, flag, _ int) (File, PipeWriter, func(), error) {
  348. client, err := fs.conn.getClient()
  349. if err != nil {
  350. return nil, nil, nil, err
  351. }
  352. if fs.config.BufferSize == 0 {
  353. var f File
  354. if flag == 0 {
  355. f, err = client.Create(name)
  356. } else {
  357. f, err = client.OpenFile(name, flag)
  358. }
  359. return f, nil, nil, err
  360. }
  361. // buffering is enabled
  362. f, err := client.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
  363. if err != nil {
  364. return nil, nil, nil, err
  365. }
  366. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  367. if err != nil {
  368. f.Close()
  369. return nil, nil, nil, err
  370. }
  371. p := NewPipeWriter(w)
  372. go func() {
  373. bw := bufio.NewWriterSize(f, int(fs.config.BufferSize)*1024*1024)
  374. // we don't use io.Copy since bufio.Writer implements io.WriterTo and
  375. // so it calls the sftp.File WriteTo method without buffering
  376. n, err := doCopy(bw, r, nil)
  377. errFlush := bw.Flush()
  378. if err == nil && errFlush != nil {
  379. err = errFlush
  380. }
  381. var errTruncate error
  382. if err != nil {
  383. errTruncate = f.Truncate(n)
  384. }
  385. errClose := f.Close()
  386. if err == nil && errClose != nil {
  387. err = errClose
  388. }
  389. r.CloseWithError(err) //nolint:errcheck
  390. p.Done(err)
  391. fsLog(fs, logger.LevelDebug, "upload completed, path: %q, readed bytes: %v, err: %v err truncate: %v",
  392. name, n, err, errTruncate)
  393. }()
  394. return nil, p, nil, nil
  395. }
  396. // Rename renames (moves) source to target.
  397. func (fs *SFTPFs) Rename(source, target string) (int, int64, error) {
  398. if source == target {
  399. return -1, -1, nil
  400. }
  401. client, err := fs.conn.getClient()
  402. if err != nil {
  403. return -1, -1, err
  404. }
  405. if _, ok := client.HasExtension("[email protected]"); ok {
  406. err := client.PosixRename(source, target)
  407. return -1, -1, err
  408. }
  409. err = client.Rename(source, target)
  410. return -1, -1, err
  411. }
  412. // Remove removes the named file or (empty) directory.
  413. func (fs *SFTPFs) Remove(name string, isDir bool) error {
  414. client, err := fs.conn.getClient()
  415. if err != nil {
  416. return err
  417. }
  418. if isDir {
  419. return client.RemoveDirectory(name)
  420. }
  421. return client.Remove(name)
  422. }
  423. // Mkdir creates a new directory with the specified name and default permissions
  424. func (fs *SFTPFs) Mkdir(name string) error {
  425. client, err := fs.conn.getClient()
  426. if err != nil {
  427. return err
  428. }
  429. return client.Mkdir(name)
  430. }
  431. // Symlink creates source as a symbolic link to target.
  432. func (fs *SFTPFs) Symlink(source, target string) error {
  433. client, err := fs.conn.getClient()
  434. if err != nil {
  435. return err
  436. }
  437. return client.Symlink(source, target)
  438. }
  439. // Readlink returns the destination of the named symbolic link
  440. func (fs *SFTPFs) Readlink(name string) (string, error) {
  441. client, err := fs.conn.getClient()
  442. if err != nil {
  443. return "", err
  444. }
  445. resolved, err := client.ReadLink(name)
  446. if err != nil {
  447. return resolved, err
  448. }
  449. resolved = path.Clean(resolved)
  450. if !path.IsAbs(resolved) {
  451. // we assume that multiple links are not followed
  452. resolved = path.Join(path.Dir(name), resolved)
  453. }
  454. return fs.GetRelativePath(resolved), nil
  455. }
  456. // Chown changes the numeric uid and gid of the named file.
  457. func (fs *SFTPFs) Chown(name string, uid int, gid int) error {
  458. client, err := fs.conn.getClient()
  459. if err != nil {
  460. return err
  461. }
  462. return client.Chown(name, uid, gid)
  463. }
  464. // Chmod changes the mode of the named file to mode.
  465. func (fs *SFTPFs) Chmod(name string, mode os.FileMode) error {
  466. client, err := fs.conn.getClient()
  467. if err != nil {
  468. return err
  469. }
  470. return client.Chmod(name, mode)
  471. }
  472. // Chtimes changes the access and modification times of the named file.
  473. func (fs *SFTPFs) Chtimes(name string, atime, mtime time.Time, _ bool) error {
  474. client, err := fs.conn.getClient()
  475. if err != nil {
  476. return err
  477. }
  478. return client.Chtimes(name, atime, mtime)
  479. }
  480. // Truncate changes the size of the named file.
  481. func (fs *SFTPFs) Truncate(name string, size int64) error {
  482. client, err := fs.conn.getClient()
  483. if err != nil {
  484. return err
  485. }
  486. return client.Truncate(name, size)
  487. }
  488. // ReadDir reads the directory named by dirname and returns
  489. // a list of directory entries.
  490. func (fs *SFTPFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  491. client, err := fs.conn.getClient()
  492. if err != nil {
  493. return nil, err
  494. }
  495. return client.ReadDir(dirname)
  496. }
  497. // IsUploadResumeSupported returns true if resuming uploads is supported.
  498. func (fs *SFTPFs) IsUploadResumeSupported() bool {
  499. return fs.config.BufferSize == 0
  500. }
  501. // IsConditionalUploadResumeSupported returns if resuming uploads is supported
  502. // for the specified size
  503. func (fs *SFTPFs) IsConditionalUploadResumeSupported(_ int64) bool {
  504. return fs.IsUploadResumeSupported()
  505. }
  506. // IsAtomicUploadSupported returns true if atomic upload is supported.
  507. func (fs *SFTPFs) IsAtomicUploadSupported() bool {
  508. return fs.config.BufferSize == 0
  509. }
  510. // IsNotExist returns a boolean indicating whether the error is known to
  511. // report that a file or directory does not exist
  512. func (*SFTPFs) IsNotExist(err error) bool {
  513. return errors.Is(err, fs.ErrNotExist)
  514. }
  515. // IsPermission returns a boolean indicating whether the error is known to
  516. // report that permission is denied.
  517. func (*SFTPFs) IsPermission(err error) bool {
  518. if _, ok := err.(*pathResolutionError); ok {
  519. return true
  520. }
  521. return errors.Is(err, fs.ErrPermission)
  522. }
  523. // IsNotSupported returns true if the error indicate an unsupported operation
  524. func (*SFTPFs) IsNotSupported(err error) bool {
  525. if err == nil {
  526. return false
  527. }
  528. return err == ErrVfsUnsupported
  529. }
  530. // CheckRootPath creates the specified local root directory if it does not exists
  531. func (fs *SFTPFs) CheckRootPath(username string, uid int, gid int) bool {
  532. // local directory for temporary files in buffer mode
  533. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "", nil)
  534. osFs.CheckRootPath(username, uid, gid)
  535. if fs.config.Prefix == "/" {
  536. return true
  537. }
  538. client, err := fs.conn.getClient()
  539. if err != nil {
  540. return false
  541. }
  542. if err := client.MkdirAll(fs.config.Prefix); err != nil {
  543. fsLog(fs, logger.LevelDebug, "error creating root directory %q for user %q: %v", fs.config.Prefix, username, err)
  544. return false
  545. }
  546. return true
  547. }
  548. // ScanRootDirContents returns the number of files contained in a directory and
  549. // their size
  550. func (fs *SFTPFs) ScanRootDirContents() (int, int64, error) {
  551. return fs.GetDirSize(fs.config.Prefix)
  552. }
  553. // CheckMetadata checks the metadata consistency
  554. func (*SFTPFs) CheckMetadata() error {
  555. return nil
  556. }
  557. // GetAtomicUploadPath returns the path to use for an atomic upload
  558. func (*SFTPFs) GetAtomicUploadPath(name string) string {
  559. dir := path.Dir(name)
  560. guid := xid.New().String()
  561. return path.Join(dir, ".sftpgo-upload."+guid+"."+path.Base(name))
  562. }
  563. // GetRelativePath returns the path for a file relative to the sftp prefix if any.
  564. // This is the path as seen by SFTPGo users
  565. func (fs *SFTPFs) GetRelativePath(name string) string {
  566. rel := path.Clean(name)
  567. if rel == "." {
  568. rel = ""
  569. }
  570. if !path.IsAbs(rel) {
  571. return "/" + rel
  572. }
  573. if fs.config.Prefix != "/" {
  574. if !strings.HasPrefix(rel, fs.config.Prefix) {
  575. rel = "/"
  576. }
  577. rel = path.Clean("/" + strings.TrimPrefix(rel, fs.config.Prefix))
  578. }
  579. if fs.mountPath != "" {
  580. rel = path.Join(fs.mountPath, rel)
  581. }
  582. return rel
  583. }
  584. // Walk walks the file tree rooted at root, calling walkFn for each file or
  585. // directory in the tree, including root
  586. func (fs *SFTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
  587. client, err := fs.conn.getClient()
  588. if err != nil {
  589. return err
  590. }
  591. walker := client.Walk(root)
  592. for walker.Step() {
  593. err := walker.Err()
  594. if err != nil {
  595. return err
  596. }
  597. err = walkFn(walker.Path(), walker.Stat(), err)
  598. if err != nil {
  599. return err
  600. }
  601. }
  602. return nil
  603. }
  604. // Join joins any number of path elements into a single path
  605. func (*SFTPFs) Join(elem ...string) string {
  606. return path.Join(elem...)
  607. }
  608. // HasVirtualFolders returns true if folders are emulated
  609. func (*SFTPFs) HasVirtualFolders() bool {
  610. return false
  611. }
  612. // ResolvePath returns the matching filesystem path for the specified virtual path
  613. func (fs *SFTPFs) ResolvePath(virtualPath string) (string, error) {
  614. if fs.mountPath != "" {
  615. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  616. }
  617. if !path.IsAbs(virtualPath) {
  618. virtualPath = path.Clean("/" + virtualPath)
  619. }
  620. fsPath := fs.Join(fs.config.Prefix, virtualPath)
  621. if fs.config.Prefix != "/" && fsPath != "/" {
  622. // we need to check if this path is a symlink outside the given prefix
  623. // or a file/dir inside a dir symlinked outside the prefix
  624. var validatedPath string
  625. var err error
  626. validatedPath, err = fs.getRealPath(fsPath)
  627. isNotExist := fs.IsNotExist(err)
  628. if err != nil && !isNotExist {
  629. fsLog(fs, logger.LevelError, "Invalid path resolution, original path %v resolved %q err: %v",
  630. virtualPath, fsPath, err)
  631. return "", err
  632. } else if isNotExist {
  633. for fs.IsNotExist(err) {
  634. validatedPath = path.Dir(validatedPath)
  635. if validatedPath == "/" {
  636. err = nil
  637. break
  638. }
  639. validatedPath, err = fs.getRealPath(validatedPath)
  640. }
  641. if err != nil {
  642. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %q original path %q resolved %q err: %v",
  643. validatedPath, virtualPath, fsPath, err)
  644. return "", err
  645. }
  646. }
  647. if err := fs.isSubDir(validatedPath); err != nil {
  648. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %q original path %q resolved %q err: %v",
  649. validatedPath, virtualPath, fsPath, err)
  650. return "", err
  651. }
  652. }
  653. return fsPath, nil
  654. }
  655. // RealPath implements the FsRealPather interface
  656. func (fs *SFTPFs) RealPath(p string) (string, error) {
  657. client, err := fs.conn.getClient()
  658. if err != nil {
  659. return "", err
  660. }
  661. resolved, err := client.RealPath(p)
  662. if err != nil {
  663. return "", err
  664. }
  665. if fs.config.Prefix != "/" {
  666. if err := fs.isSubDir(resolved); err != nil {
  667. fsLog(fs, logger.LevelError, "Invalid real path resolution, original path %q resolved %q err: %v",
  668. p, resolved, err)
  669. return "", err
  670. }
  671. }
  672. return fs.GetRelativePath(resolved), nil
  673. }
  674. // getRealPath returns the real remote path trying to resolve symbolic links if any
  675. func (fs *SFTPFs) getRealPath(name string) (string, error) {
  676. client, err := fs.conn.getClient()
  677. if err != nil {
  678. return "", err
  679. }
  680. linksWalked := 0
  681. for {
  682. info, err := client.Lstat(name)
  683. if err != nil {
  684. return name, err
  685. }
  686. if info.Mode()&os.ModeSymlink == 0 {
  687. return name, nil
  688. }
  689. resolvedLink, err := client.ReadLink(name)
  690. if err != nil {
  691. return name, fmt.Errorf("unable to resolve link to %q: %w", name, err)
  692. }
  693. resolvedLink = path.Clean(resolvedLink)
  694. if path.IsAbs(resolvedLink) {
  695. name = resolvedLink
  696. } else {
  697. name = path.Join(path.Dir(name), resolvedLink)
  698. }
  699. linksWalked++
  700. if linksWalked > 10 {
  701. fsLog(fs, logger.LevelError, "unable to get real path, too many links: %d", linksWalked)
  702. return "", &pathResolutionError{err: "too many links"}
  703. }
  704. }
  705. }
  706. func (fs *SFTPFs) isSubDir(name string) error {
  707. if name == fs.config.Prefix {
  708. return nil
  709. }
  710. if len(name) < len(fs.config.Prefix) {
  711. err := fmt.Errorf("path %q is not inside: %q", name, fs.config.Prefix)
  712. return &pathResolutionError{err: err.Error()}
  713. }
  714. if !strings.HasPrefix(name, fs.config.Prefix+"/") {
  715. err := fmt.Errorf("path %q is not inside: %q", name, fs.config.Prefix)
  716. return &pathResolutionError{err: err.Error()}
  717. }
  718. return nil
  719. }
  720. // GetDirSize returns the number of files and the size for a folder
  721. // including any subfolders
  722. func (fs *SFTPFs) GetDirSize(dirname string) (int, int64, error) {
  723. numFiles := 0
  724. size := int64(0)
  725. client, err := fs.conn.getClient()
  726. if err != nil {
  727. return numFiles, size, err
  728. }
  729. isDir, err := isDirectory(fs, dirname)
  730. if err == nil && isDir {
  731. walker := client.Walk(dirname)
  732. for walker.Step() {
  733. err := walker.Err()
  734. if err != nil {
  735. return numFiles, size, err
  736. }
  737. if walker.Stat().Mode().IsRegular() {
  738. size += walker.Stat().Size()
  739. numFiles++
  740. if numFiles%1000 == 0 {
  741. fsLog(fs, logger.LevelDebug, "dirname %q scan in progress, files: %d, size: %d", dirname, numFiles, size)
  742. }
  743. }
  744. }
  745. }
  746. return numFiles, size, err
  747. }
  748. // GetMimeType returns the content type
  749. func (fs *SFTPFs) GetMimeType(name string) (string, error) {
  750. client, err := fs.conn.getClient()
  751. if err != nil {
  752. return "", err
  753. }
  754. f, err := client.OpenFile(name, os.O_RDONLY)
  755. if err != nil {
  756. return "", err
  757. }
  758. defer f.Close()
  759. var buf [512]byte
  760. n, err := io.ReadFull(f, buf[:])
  761. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  762. return "", err
  763. }
  764. ctype := http.DetectContentType(buf[:n])
  765. // Rewind file.
  766. _, err = f.Seek(0, io.SeekStart)
  767. return ctype, err
  768. }
  769. // GetAvailableDiskSize returns the available size for the specified path
  770. func (fs *SFTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  771. client, err := fs.conn.getClient()
  772. if err != nil {
  773. return nil, err
  774. }
  775. if _, ok := client.HasExtension("[email protected]"); !ok {
  776. return nil, ErrStorageSizeUnavailable
  777. }
  778. return client.StatVFS(dirName)
  779. }
  780. // Close the connection
  781. func (fs *SFTPFs) Close() error {
  782. fs.conn.RemoveSession(fs.connectionID)
  783. return nil
  784. }
  785. func (fs *SFTPFs) createConnection() error {
  786. err := fs.conn.OpenConnection()
  787. if err != nil {
  788. fsLog(fs, logger.LevelError, "error opening connection: %v", err)
  789. return err
  790. }
  791. return nil
  792. }
  793. type sftpConnection struct {
  794. config *SFTPFsConfig
  795. logSender string
  796. sshClient *ssh.Client
  797. sftpClient *sftp.Client
  798. mu sync.RWMutex
  799. isConnected bool
  800. sessions map[string]bool
  801. lastActivity time.Time
  802. }
  803. func newSFTPConnection(config *SFTPFsConfig, sessionID string) *sftpConnection {
  804. c := &sftpConnection{
  805. config: config,
  806. logSender: fmt.Sprintf(`%s "%s@%s"`, sftpFsName, config.Username, config.Endpoint),
  807. isConnected: false,
  808. sessions: map[string]bool{},
  809. lastActivity: time.Now().UTC(),
  810. }
  811. c.sessions[sessionID] = true
  812. return c
  813. }
  814. func (c *sftpConnection) OpenConnection() error {
  815. c.mu.Lock()
  816. defer c.mu.Unlock()
  817. return c.openConnNoLock()
  818. }
  819. func (c *sftpConnection) openConnNoLock() error {
  820. if c.isConnected {
  821. logger.Debug(c.logSender, "", "reusing connection")
  822. return nil
  823. }
  824. logger.Debug(c.logSender, "", "try to open a new connection")
  825. clientConfig := &ssh.ClientConfig{
  826. User: c.config.Username,
  827. HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
  828. fp := ssh.FingerprintSHA256(key)
  829. if util.Contains(sftpFingerprints, fp) {
  830. if allowSelfConnections == 0 {
  831. logger.Log(logger.LevelError, c.logSender, "", "SFTP self connections not allowed")
  832. return ErrSFTPLoop
  833. }
  834. if util.Contains(c.config.forbiddenSelfUsernames, c.config.Username) {
  835. logger.Log(logger.LevelError, c.logSender, "",
  836. "SFTP loop or nested local SFTP folders detected, username %q, forbidden usernames: %+v",
  837. c.config.Username, c.config.forbiddenSelfUsernames)
  838. return ErrSFTPLoop
  839. }
  840. }
  841. if len(c.config.Fingerprints) > 0 {
  842. for _, provided := range c.config.Fingerprints {
  843. if provided == fp {
  844. return nil
  845. }
  846. }
  847. return fmt.Errorf("invalid fingerprint %q", fp)
  848. }
  849. logger.Log(logger.LevelWarn, c.logSender, "", "login without host key validation, please provide at least a fingerprint!")
  850. return nil
  851. },
  852. Timeout: 10 * time.Second,
  853. ClientVersion: fmt.Sprintf("SSH-2.0-SFTPGo_%v", version.Get().Version),
  854. }
  855. if c.config.PrivateKey.GetPayload() != "" {
  856. var signer ssh.Signer
  857. var err error
  858. if c.config.KeyPassphrase.GetPayload() != "" {
  859. signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(c.config.PrivateKey.GetPayload()),
  860. []byte(c.config.KeyPassphrase.GetPayload()))
  861. } else {
  862. signer, err = ssh.ParsePrivateKey([]byte(c.config.PrivateKey.GetPayload()))
  863. }
  864. if err != nil {
  865. return fmt.Errorf("sftpfs: unable to parse the private key: %w", err)
  866. }
  867. clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
  868. }
  869. if c.config.Password.GetPayload() != "" {
  870. clientConfig.Auth = append(clientConfig.Auth, ssh.Password(c.config.Password.GetPayload()))
  871. }
  872. // add more ciphers, KEXs and MACs, they are negotiated according to the order
  873. clientConfig.Ciphers = []string{"[email protected]", "[email protected]", "[email protected]",
  874. "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-cbc", "aes192-cbc", "aes256-cbc"}
  875. clientConfig.KeyExchanges = []string{"curve25519-sha256", "[email protected]",
  876. "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
  877. "diffie-hellman-group14-sha256", "diffie-hellman-group-exchange-sha256",
  878. "diffie-hellman-group16-sha512", "diffie-hellman-group-exchange-sha1",
  879. "diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1"}
  880. clientConfig.MACs = []string{"[email protected]", "hmac-sha2-256",
  881. "[email protected]", "hmac-sha2-512",
  882. "hmac-sha1", "hmac-sha1-96"}
  883. sshClient, err := ssh.Dial("tcp", c.config.Endpoint, clientConfig)
  884. if err != nil {
  885. return fmt.Errorf("sftpfs: unable to connect: %w", err)
  886. }
  887. sftpClient, err := sftp.NewClient(sshClient, c.getClientOptions()...)
  888. if err != nil {
  889. sshClient.Close()
  890. return fmt.Errorf("sftpfs: unable to create SFTP client: %w", err)
  891. }
  892. c.sshClient = sshClient
  893. c.sftpClient = sftpClient
  894. c.isConnected = true
  895. go c.Wait()
  896. return nil
  897. }
  898. func (c *sftpConnection) getClientOptions() []sftp.ClientOption {
  899. var options []sftp.ClientOption
  900. if c.config.DisableCouncurrentReads {
  901. options = append(options, sftp.UseConcurrentReads(false))
  902. logger.Debug(c.logSender, "", "disabling concurrent reads")
  903. }
  904. if c.config.BufferSize > 0 {
  905. options = append(options, sftp.UseConcurrentWrites(true))
  906. logger.Debug(c.logSender, "", "enabling concurrent writes")
  907. }
  908. return options
  909. }
  910. func (c *sftpConnection) getClient() (*sftp.Client, error) {
  911. c.mu.Lock()
  912. defer c.mu.Unlock()
  913. if c.isConnected {
  914. return c.sftpClient, nil
  915. }
  916. err := c.openConnNoLock()
  917. return c.sftpClient, err
  918. }
  919. func (c *sftpConnection) Wait() {
  920. done := make(chan struct{})
  921. go func() {
  922. var watchdogInProgress atomic.Bool
  923. ticker := time.NewTicker(30 * time.Second)
  924. defer ticker.Stop()
  925. for {
  926. select {
  927. case <-ticker.C:
  928. if watchdogInProgress.Load() {
  929. logger.Error(c.logSender, "", "watchdog still in progress, closing hanging connection")
  930. c.sshClient.Close()
  931. return
  932. }
  933. go func() {
  934. watchdogInProgress.Store(true)
  935. defer watchdogInProgress.Store(false)
  936. _, err := c.sftpClient.Getwd()
  937. if err != nil {
  938. logger.Error(c.logSender, "", "watchdog error: %v", err)
  939. }
  940. }()
  941. case <-done:
  942. logger.Debug(c.logSender, "", "quitting watchdog")
  943. return
  944. }
  945. }
  946. }()
  947. // we wait on the sftp client otherwise if the channel is closed but not the connection
  948. // we don't detect the event.
  949. err := c.sftpClient.Wait()
  950. logger.Log(logger.LevelDebug, c.logSender, "", "sftp channel closed: %v", err)
  951. close(done)
  952. c.mu.Lock()
  953. defer c.mu.Unlock()
  954. c.isConnected = false
  955. if c.sshClient != nil {
  956. c.sshClient.Close()
  957. }
  958. }
  959. func (c *sftpConnection) Close() error {
  960. c.mu.Lock()
  961. defer c.mu.Unlock()
  962. logger.Debug(c.logSender, "", "closing connection")
  963. var sftpErr, sshErr error
  964. if c.sftpClient != nil {
  965. sftpErr = c.sftpClient.Close()
  966. }
  967. if c.sshClient != nil {
  968. sshErr = c.sshClient.Close()
  969. }
  970. if sftpErr != nil {
  971. return sftpErr
  972. }
  973. c.isConnected = false
  974. return sshErr
  975. }
  976. func (c *sftpConnection) AddSession(sessionID string) {
  977. c.mu.Lock()
  978. defer c.mu.Unlock()
  979. c.sessions[sessionID] = true
  980. logger.Debug(c.logSender, "", "added session %s, active sessions: %d", sessionID, len(c.sessions))
  981. }
  982. func (c *sftpConnection) RemoveSession(sessionID string) {
  983. c.mu.Lock()
  984. defer c.mu.Unlock()
  985. delete(c.sessions, sessionID)
  986. logger.Debug(c.logSender, "", "removed session %s, active sessions: %d", sessionID, len(c.sessions))
  987. if len(c.sessions) == 0 {
  988. c.lastActivity = time.Now().UTC()
  989. }
  990. }
  991. func (c *sftpConnection) ActiveSessions() int {
  992. c.mu.RLock()
  993. defer c.mu.RUnlock()
  994. return len(c.sessions)
  995. }
  996. func (c *sftpConnection) GetLastActivity() time.Time {
  997. c.mu.RLock()
  998. defer c.mu.RUnlock()
  999. if len(c.sessions) > 0 {
  1000. return time.Now().UTC()
  1001. }
  1002. logger.Debug(c.logSender, "", "last activity %s", c.lastActivity)
  1003. return c.lastActivity
  1004. }
  1005. type sftpConnectionsCache struct {
  1006. scheduler *cron.Cron
  1007. sync.RWMutex
  1008. items map[uint64]*sftpConnection
  1009. }
  1010. func newSFTPConnectionCache() *sftpConnectionsCache {
  1011. c := &sftpConnectionsCache{
  1012. scheduler: cron.New(cron.WithLocation(time.UTC), cron.WithLogger(cron.DiscardLogger)),
  1013. items: make(map[uint64]*sftpConnection),
  1014. }
  1015. _, err := c.scheduler.AddFunc("@every 1m", c.Cleanup)
  1016. util.PanicOnError(err)
  1017. c.scheduler.Start()
  1018. return c
  1019. }
  1020. func (c *sftpConnectionsCache) Get(config *SFTPFsConfig, sessionID string) *sftpConnection {
  1021. partition := 0
  1022. key := config.getUniqueID(partition)
  1023. c.Lock()
  1024. defer c.Unlock()
  1025. var oldKey uint64
  1026. for {
  1027. if val, ok := c.items[key]; ok {
  1028. activeSessions := val.ActiveSessions()
  1029. if activeSessions < maxSessionsPerConnection || key == oldKey {
  1030. logger.Debug(logSenderSFTPCache, "",
  1031. "reusing connection for session ID %q, key: %d, active sessions %d, active connections: %d",
  1032. sessionID, key, activeSessions+1, len(c.items))
  1033. val.AddSession(sessionID)
  1034. return val
  1035. }
  1036. partition++
  1037. oldKey = key
  1038. key = config.getUniqueID(partition)
  1039. logger.Debug(logSenderSFTPCache, "",
  1040. "connection full, generated new key for partition: %d, active sessions: %d, key: %d, old key: %d",
  1041. partition, activeSessions, oldKey, key)
  1042. } else {
  1043. conn := newSFTPConnection(config, sessionID)
  1044. c.items[key] = conn
  1045. logger.Debug(logSenderSFTPCache, "",
  1046. "adding new connection for session ID %q, partition: %d, key: %d, active connections: %d",
  1047. sessionID, partition, key, len(c.items))
  1048. return conn
  1049. }
  1050. }
  1051. }
  1052. func (c *sftpConnectionsCache) Remove(key uint64) {
  1053. c.Lock()
  1054. defer c.Unlock()
  1055. if conn, ok := c.items[key]; ok {
  1056. delete(c.items, key)
  1057. logger.Debug(logSenderSFTPCache, "", "removed connection with key %d, active connections: %d", key, len(c.items))
  1058. defer conn.Close()
  1059. }
  1060. }
  1061. func (c *sftpConnectionsCache) Cleanup() {
  1062. c.RLock()
  1063. for k, conn := range c.items {
  1064. if val := conn.GetLastActivity(); val.Before(time.Now().Add(-30 * time.Second)) {
  1065. logger.Debug(conn.logSender, "", "removing inactive connection, last activity %s", val)
  1066. defer func(key uint64) {
  1067. c.Remove(key)
  1068. }(k)
  1069. }
  1070. }
  1071. c.RUnlock()
  1072. }