vfs.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // Package vfs provides local and remote filesystems support
  2. package vfs
  3. import (
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/url"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "time"
  14. "github.com/eikenb/pipeat"
  15. "github.com/pkg/sftp"
  16. "github.com/drakkan/sftpgo/kms"
  17. "github.com/drakkan/sftpgo/logger"
  18. "github.com/drakkan/sftpgo/utils"
  19. )
  20. const dirMimeType = "inode/directory"
  21. var (
  22. validAzAccessTier = []string{"", "Archive", "Hot", "Cool"}
  23. // ErrStorageSizeUnavailable is returned if the storage backend does not support getting the size
  24. ErrStorageSizeUnavailable = errors.New("unable to get available size for this storage backend")
  25. )
  26. // Fs defines the interface for filesystem backends
  27. type Fs interface {
  28. Name() string
  29. ConnectionID() string
  30. Stat(name string) (os.FileInfo, error)
  31. Lstat(name string) (os.FileInfo, error)
  32. Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error)
  33. Create(name string, flag int) (File, *PipeWriter, func(), error)
  34. Rename(source, target string) error
  35. Remove(name string, isDir bool) error
  36. Mkdir(name string) error
  37. Symlink(source, target string) error
  38. Chown(name string, uid int, gid int) error
  39. Chmod(name string, mode os.FileMode) error
  40. Chtimes(name string, atime, mtime time.Time) error
  41. Truncate(name string, size int64) error
  42. ReadDir(dirname string) ([]os.FileInfo, error)
  43. Readlink(name string) (string, error)
  44. IsUploadResumeSupported() bool
  45. IsAtomicUploadSupported() bool
  46. CheckRootPath(username string, uid int, gid int) bool
  47. ResolvePath(sftpPath string) (string, error)
  48. IsNotExist(err error) bool
  49. IsPermission(err error) bool
  50. IsNotSupported(err error) bool
  51. ScanRootDirContents() (int, int64, error)
  52. GetDirSize(dirname string) (int, int64, error)
  53. GetAtomicUploadPath(name string) string
  54. GetRelativePath(name string) string
  55. Walk(root string, walkFn filepath.WalkFunc) error
  56. Join(elem ...string) string
  57. HasVirtualFolders() bool
  58. GetMimeType(name string) (string, error)
  59. GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error)
  60. Close() error
  61. }
  62. // File defines an interface representing a SFTPGo file
  63. type File interface {
  64. io.Reader
  65. io.Writer
  66. io.Closer
  67. io.ReaderAt
  68. io.WriterAt
  69. io.Seeker
  70. Stat() (os.FileInfo, error)
  71. Name() string
  72. Truncate(size int64) error
  73. }
  74. // ErrVfsUnsupported defines the error for an unsupported VFS operation
  75. var ErrVfsUnsupported = errors.New("Not supported")
  76. // QuotaCheckResult defines the result for a quota check
  77. type QuotaCheckResult struct {
  78. HasSpace bool
  79. AllowedSize int64
  80. AllowedFiles int
  81. UsedSize int64
  82. UsedFiles int
  83. QuotaSize int64
  84. QuotaFiles int
  85. }
  86. // GetRemainingSize returns the remaining allowed size
  87. func (q *QuotaCheckResult) GetRemainingSize() int64 {
  88. if q.QuotaSize > 0 {
  89. return q.QuotaSize - q.UsedSize
  90. }
  91. return 0
  92. }
  93. // GetRemainingFiles returns the remaining allowed files
  94. func (q *QuotaCheckResult) GetRemainingFiles() int {
  95. if q.QuotaFiles > 0 {
  96. return q.QuotaFiles - q.UsedFiles
  97. }
  98. return 0
  99. }
  100. // S3FsConfig defines the configuration for S3 based filesystem
  101. type S3FsConfig struct {
  102. Bucket string `json:"bucket,omitempty"`
  103. // KeyPrefix is similar to a chroot directory for local filesystem.
  104. // If specified then the SFTP user will only see objects that starts
  105. // with this prefix and so you can restrict access to a specific
  106. // folder. The prefix, if not empty, must not start with "/" and must
  107. // end with "/".
  108. // If empty the whole bucket contents will be available
  109. KeyPrefix string `json:"key_prefix,omitempty"`
  110. Region string `json:"region,omitempty"`
  111. AccessKey string `json:"access_key,omitempty"`
  112. AccessSecret *kms.Secret `json:"access_secret,omitempty"`
  113. Endpoint string `json:"endpoint,omitempty"`
  114. StorageClass string `json:"storage_class,omitempty"`
  115. // The buffer size (in MB) to use for multipart uploads. The minimum allowed part size is 5MB,
  116. // and if this value is set to zero, the default value (5MB) for the AWS SDK will be used.
  117. // The minimum allowed value is 5.
  118. // Please note that if the upload bandwidth between the SFTP client and SFTPGo is greater than
  119. // the upload bandwidth between SFTPGo and S3 then the SFTP client have to wait for the upload
  120. // of the last parts to S3 after it ends the file upload to SFTPGo, and it may time out.
  121. // Keep this in mind if you customize these parameters.
  122. UploadPartSize int64 `json:"upload_part_size,omitempty"`
  123. // How many parts are uploaded in parallel
  124. UploadConcurrency int `json:"upload_concurrency,omitempty"`
  125. }
  126. func (c *S3FsConfig) checkCredentials() error {
  127. if c.AccessKey == "" && !c.AccessSecret.IsEmpty() {
  128. return errors.New("access_key cannot be empty with access_secret not empty")
  129. }
  130. if c.AccessSecret.IsEmpty() && c.AccessKey != "" {
  131. return errors.New("access_secret cannot be empty with access_key not empty")
  132. }
  133. if c.AccessSecret.IsEncrypted() && !c.AccessSecret.IsValid() {
  134. return errors.New("invalid encrypted access_secret")
  135. }
  136. if !c.AccessSecret.IsEmpty() && !c.AccessSecret.IsValidInput() {
  137. return errors.New("invalid access_secret")
  138. }
  139. return nil
  140. }
  141. // EncryptCredentials encrypts access secret if it is in plain text
  142. func (c *S3FsConfig) EncryptCredentials(additionalData string) error {
  143. if c.AccessSecret.IsPlain() {
  144. c.AccessSecret.SetAdditionalData(additionalData)
  145. err := c.AccessSecret.Encrypt()
  146. if err != nil {
  147. return err
  148. }
  149. }
  150. return nil
  151. }
  152. // Validate returns an error if the configuration is not valid
  153. func (c *S3FsConfig) Validate() error {
  154. if c.AccessSecret == nil {
  155. c.AccessSecret = kms.NewEmptySecret()
  156. }
  157. if c.Bucket == "" {
  158. return errors.New("bucket cannot be empty")
  159. }
  160. if c.Region == "" {
  161. return errors.New("region cannot be empty")
  162. }
  163. if err := c.checkCredentials(); err != nil {
  164. return err
  165. }
  166. if c.KeyPrefix != "" {
  167. if strings.HasPrefix(c.KeyPrefix, "/") {
  168. return errors.New("key_prefix cannot start with /")
  169. }
  170. c.KeyPrefix = path.Clean(c.KeyPrefix)
  171. if !strings.HasSuffix(c.KeyPrefix, "/") {
  172. c.KeyPrefix += "/"
  173. }
  174. }
  175. if c.UploadPartSize != 0 && (c.UploadPartSize < 5 || c.UploadPartSize > 5000) {
  176. return errors.New("upload_part_size cannot be != 0, lower than 5 (MB) or greater than 5000 (MB)")
  177. }
  178. if c.UploadConcurrency < 0 || c.UploadConcurrency > 64 {
  179. return fmt.Errorf("invalid upload concurrency: %v", c.UploadConcurrency)
  180. }
  181. return nil
  182. }
  183. // GCSFsConfig defines the configuration for Google Cloud Storage based filesystem
  184. type GCSFsConfig struct {
  185. Bucket string `json:"bucket,omitempty"`
  186. // KeyPrefix is similar to a chroot directory for local filesystem.
  187. // If specified then the SFTP user will only see objects that starts
  188. // with this prefix and so you can restrict access to a specific
  189. // folder. The prefix, if not empty, must not start with "/" and must
  190. // end with "/".
  191. // If empty the whole bucket contents will be available
  192. KeyPrefix string `json:"key_prefix,omitempty"`
  193. CredentialFile string `json:"-"`
  194. Credentials *kms.Secret `json:"credentials,omitempty"`
  195. // 0 explicit, 1 automatic
  196. AutomaticCredentials int `json:"automatic_credentials,omitempty"`
  197. StorageClass string `json:"storage_class,omitempty"`
  198. }
  199. // Validate returns an error if the configuration is not valid
  200. func (c *GCSFsConfig) Validate(credentialsFilePath string) error {
  201. if c.Credentials == nil {
  202. c.Credentials = kms.NewEmptySecret()
  203. }
  204. if c.Bucket == "" {
  205. return errors.New("bucket cannot be empty")
  206. }
  207. if c.KeyPrefix != "" {
  208. if strings.HasPrefix(c.KeyPrefix, "/") {
  209. return errors.New("key_prefix cannot start with /")
  210. }
  211. c.KeyPrefix = path.Clean(c.KeyPrefix)
  212. if !strings.HasSuffix(c.KeyPrefix, "/") {
  213. c.KeyPrefix += "/"
  214. }
  215. }
  216. if c.Credentials.IsEncrypted() && !c.Credentials.IsValid() {
  217. return errors.New("invalid encrypted credentials")
  218. }
  219. if !c.Credentials.IsValidInput() && c.AutomaticCredentials == 0 {
  220. fi, err := os.Stat(credentialsFilePath)
  221. if err != nil {
  222. return fmt.Errorf("invalid credentials %v", err)
  223. }
  224. if fi.Size() == 0 {
  225. return errors.New("credentials cannot be empty")
  226. }
  227. }
  228. return nil
  229. }
  230. // AzBlobFsConfig defines the configuration for Azure Blob Storage based filesystem
  231. type AzBlobFsConfig struct {
  232. Container string `json:"container,omitempty"`
  233. // Storage Account Name, leave blank to use SAS URL
  234. AccountName string `json:"account_name,omitempty"`
  235. // Storage Account Key leave blank to use SAS URL.
  236. // The access key is stored encrypted based on the kms configuration
  237. AccountKey *kms.Secret `json:"account_key,omitempty"`
  238. // Optional endpoint. Default is "blob.core.windows.net".
  239. // If you use the emulator the endpoint must include the protocol,
  240. // for example "http://127.0.0.1:10000"
  241. Endpoint string `json:"endpoint,omitempty"`
  242. // Shared access signature URL, leave blank if using account/key
  243. SASURL string `json:"sas_url,omitempty"`
  244. // KeyPrefix is similar to a chroot directory for local filesystem.
  245. // If specified then the SFTPGo userd will only see objects that starts
  246. // with this prefix and so you can restrict access to a specific
  247. // folder. The prefix, if not empty, must not start with "/" and must
  248. // end with "/".
  249. // If empty the whole bucket contents will be available
  250. KeyPrefix string `json:"key_prefix,omitempty"`
  251. // The buffer size (in MB) to use for multipart uploads.
  252. // If this value is set to zero, the default value (1MB) for the Azure SDK will be used.
  253. // Please note that if the upload bandwidth between the SFTPGo client and SFTPGo server is
  254. // greater than the upload bandwidth between SFTPGo and Azure then the SFTP client have
  255. // to wait for the upload of the last parts to Azure after it ends the file upload to SFTPGo,
  256. // and it may time out.
  257. // Keep this in mind if you customize these parameters.
  258. UploadPartSize int64 `json:"upload_part_size,omitempty"`
  259. // How many parts are uploaded in parallel
  260. UploadConcurrency int `json:"upload_concurrency,omitempty"`
  261. // Set to true if you use an Azure emulator such as Azurite
  262. UseEmulator bool `json:"use_emulator,omitempty"`
  263. // Blob Access Tier
  264. AccessTier string `json:"access_tier,omitempty"`
  265. }
  266. // EncryptCredentials encrypts access secret if it is in plain text
  267. func (c *AzBlobFsConfig) EncryptCredentials(additionalData string) error {
  268. if c.AccountKey.IsPlain() {
  269. c.AccountKey.SetAdditionalData(additionalData)
  270. if err := c.AccountKey.Encrypt(); err != nil {
  271. return err
  272. }
  273. }
  274. return nil
  275. }
  276. func (c *AzBlobFsConfig) checkCredentials() error {
  277. if c.AccountName == "" || !c.AccountKey.IsValidInput() {
  278. return errors.New("credentials cannot be empty or invalid")
  279. }
  280. if c.AccountKey.IsEncrypted() && !c.AccountKey.IsValid() {
  281. return errors.New("invalid encrypted account_key")
  282. }
  283. return nil
  284. }
  285. // Validate returns an error if the configuration is not valid
  286. func (c *AzBlobFsConfig) Validate() error {
  287. if c.AccountKey == nil {
  288. c.AccountKey = kms.NewEmptySecret()
  289. }
  290. if c.SASURL != "" {
  291. _, err := url.Parse(c.SASURL)
  292. return err
  293. }
  294. if c.Container == "" {
  295. return errors.New("container cannot be empty")
  296. }
  297. if err := c.checkCredentials(); err != nil {
  298. return err
  299. }
  300. if c.KeyPrefix != "" {
  301. if strings.HasPrefix(c.KeyPrefix, "/") {
  302. return errors.New("key_prefix cannot start with /")
  303. }
  304. c.KeyPrefix = path.Clean(c.KeyPrefix)
  305. if !strings.HasSuffix(c.KeyPrefix, "/") {
  306. c.KeyPrefix += "/"
  307. }
  308. }
  309. if c.UploadPartSize < 0 || c.UploadPartSize > 100 {
  310. return fmt.Errorf("invalid upload part size: %v", c.UploadPartSize)
  311. }
  312. if c.UploadConcurrency < 0 || c.UploadConcurrency > 64 {
  313. return fmt.Errorf("invalid upload concurrency: %v", c.UploadConcurrency)
  314. }
  315. if !utils.IsStringInSlice(c.AccessTier, validAzAccessTier) {
  316. return fmt.Errorf("invalid access tier %#v, valid values: \"''%v\"", c.AccessTier, strings.Join(validAzAccessTier, ", "))
  317. }
  318. return nil
  319. }
  320. // CryptFsConfig defines the configuration to store local files as encrypted
  321. type CryptFsConfig struct {
  322. Passphrase *kms.Secret `json:"passphrase,omitempty"`
  323. }
  324. // EncryptCredentials encrypts access secret if it is in plain text
  325. func (c *CryptFsConfig) EncryptCredentials(additionalData string) error {
  326. if c.Passphrase.IsPlain() {
  327. c.Passphrase.SetAdditionalData(additionalData)
  328. if err := c.Passphrase.Encrypt(); err != nil {
  329. return err
  330. }
  331. }
  332. return nil
  333. }
  334. // Validate returns an error if the configuration is not valid
  335. func (c *CryptFsConfig) Validate() error {
  336. if c.Passphrase == nil || c.Passphrase.IsEmpty() {
  337. return errors.New("invalid passphrase")
  338. }
  339. if !c.Passphrase.IsValidInput() {
  340. return errors.New("passphrase cannot be empty or invalid")
  341. }
  342. if c.Passphrase.IsEncrypted() && !c.Passphrase.IsValid() {
  343. return errors.New("invalid encrypted passphrase")
  344. }
  345. return nil
  346. }
  347. // PipeWriter defines a wrapper for pipeat.PipeWriterAt.
  348. type PipeWriter struct {
  349. writer *pipeat.PipeWriterAt
  350. err error
  351. done chan bool
  352. }
  353. // NewPipeWriter initializes a new PipeWriter
  354. func NewPipeWriter(w *pipeat.PipeWriterAt) *PipeWriter {
  355. return &PipeWriter{
  356. writer: w,
  357. err: nil,
  358. done: make(chan bool),
  359. }
  360. }
  361. // Close waits for the upload to end, closes the pipeat.PipeWriterAt and returns an error if any.
  362. func (p *PipeWriter) Close() error {
  363. p.writer.Close() //nolint:errcheck // the returned error is always null
  364. <-p.done
  365. return p.err
  366. }
  367. // Done unlocks other goroutines waiting on Close().
  368. // It must be called when the upload ends
  369. func (p *PipeWriter) Done(err error) {
  370. p.err = err
  371. p.done <- true
  372. }
  373. // WriteAt is a wrapper for pipeat WriteAt
  374. func (p *PipeWriter) WriteAt(data []byte, off int64) (int, error) {
  375. return p.writer.WriteAt(data, off)
  376. }
  377. // Write is a wrapper for pipeat Write
  378. func (p *PipeWriter) Write(data []byte) (int, error) {
  379. return p.writer.Write(data)
  380. }
  381. // IsDirectory checks if a path exists and is a directory
  382. func IsDirectory(fs Fs, path string) (bool, error) {
  383. fileInfo, err := fs.Stat(path)
  384. if err != nil {
  385. return false, err
  386. }
  387. return fileInfo.IsDir(), err
  388. }
  389. // IsLocalOsFs returns true if fs is a local filesystem implementation
  390. func IsLocalOsFs(fs Fs) bool {
  391. return fs.Name() == osFsName
  392. }
  393. // IsCryptOsFs returns true if fs is an encrypted local filesystem implementation
  394. func IsCryptOsFs(fs Fs) bool {
  395. return fs.Name() == cryptFsName
  396. }
  397. // IsSFTPFs returns true if fs is an SFTP filesystem
  398. func IsSFTPFs(fs Fs) bool {
  399. return strings.HasPrefix(fs.Name(), sftpFsName)
  400. }
  401. // IsLocalOrSFTPFs returns true if fs is local or SFTP
  402. func IsLocalOrSFTPFs(fs Fs) bool {
  403. return IsLocalOsFs(fs) || IsSFTPFs(fs)
  404. }
  405. // SetPathPermissions calls fs.Chown.
  406. // It does nothing for local filesystem on windows
  407. func SetPathPermissions(fs Fs, path string, uid int, gid int) {
  408. if uid == -1 && gid == -1 {
  409. return
  410. }
  411. if IsLocalOsFs(fs) {
  412. if runtime.GOOS == "windows" {
  413. return
  414. }
  415. }
  416. if err := fs.Chown(path, uid, gid); err != nil {
  417. fsLog(fs, logger.LevelWarn, "error chowning path %v: %v", path, err)
  418. }
  419. }
  420. func fsLog(fs Fs, level logger.LogLevel, format string, v ...interface{}) {
  421. logger.Log(level, fs.Name(), fs.ConnectionID(), format, v...)
  422. }