vfs.go 15 KB

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