vfs.go 14 KB

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