vfs.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Package vfs provides local and remote filesystems support
  2. package vfs
  3. import (
  4. "errors"
  5. "fmt"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "time"
  12. "github.com/eikenb/pipeat"
  13. "github.com/drakkan/sftpgo/logger"
  14. )
  15. // Fs defines the interface for filesystem backends
  16. type Fs interface {
  17. Name() string
  18. ConnectionID() string
  19. Stat(name string) (os.FileInfo, error)
  20. Lstat(name string) (os.FileInfo, error)
  21. Open(name string) (*os.File, *pipeat.PipeReaderAt, func(), error)
  22. Create(name string, flag int) (*os.File, *PipeWriter, func(), error)
  23. Rename(source, target string) error
  24. Remove(name string, isDir bool) error
  25. Mkdir(name string) error
  26. Symlink(source, target string) error
  27. Chown(name string, uid int, gid int) error
  28. Chmod(name string, mode os.FileMode) error
  29. Chtimes(name string, atime, mtime time.Time) error
  30. ReadDir(dirname string) ([]os.FileInfo, error)
  31. IsUploadResumeSupported() bool
  32. IsAtomicUploadSupported() bool
  33. CheckRootPath(username string, uid int, gid int) bool
  34. ResolvePath(sftpPath string) (string, error)
  35. IsNotExist(err error) bool
  36. IsPermission(err error) bool
  37. ScanRootDirContents() (int, int64, error)
  38. GetDirSize(dirname string) (int, int64, error)
  39. GetAtomicUploadPath(name string) string
  40. GetRelativePath(name string) string
  41. Walk(root string, walkFn filepath.WalkFunc) error
  42. Join(elem ...string) string
  43. }
  44. var errUnsupported = errors.New("Not supported")
  45. // QuotaCheckResult defines the result for a quota check
  46. type QuotaCheckResult struct {
  47. HasSpace bool
  48. AllowedSize int64
  49. AllowedFiles int
  50. UsedSize int64
  51. UsedFiles int
  52. QuotaSize int64
  53. QuotaFiles int
  54. }
  55. // GetRemainingSize returns the remaining allowed size
  56. func (q *QuotaCheckResult) GetRemainingSize() int64 {
  57. if q.QuotaSize > 0 {
  58. return q.QuotaSize - q.UsedSize
  59. }
  60. return 0
  61. }
  62. // GetRemainingFiles returns the remaining allowed files
  63. func (q *QuotaCheckResult) GetRemainingFiles() int {
  64. if q.QuotaFiles > 0 {
  65. return q.QuotaFiles - q.UsedFiles
  66. }
  67. return 0
  68. }
  69. // S3FsConfig defines the configuration for S3 based filesystem
  70. type S3FsConfig struct {
  71. Bucket string `json:"bucket,omitempty"`
  72. // KeyPrefix is similar to a chroot directory for local filesystem.
  73. // If specified then the SFTP user will only see objects that starts
  74. // with this prefix and so you can restrict access to a specific
  75. // folder. The prefix, if not empty, must not start with "/" and must
  76. // end with "/".
  77. // If empty the whole bucket contents will be available
  78. KeyPrefix string `json:"key_prefix,omitempty"`
  79. Region string `json:"region,omitempty"`
  80. AccessKey string `json:"access_key,omitempty"`
  81. AccessSecret string `json:"access_secret,omitempty"`
  82. Endpoint string `json:"endpoint,omitempty"`
  83. StorageClass string `json:"storage_class,omitempty"`
  84. // The buffer size (in MB) to use for multipart uploads. The minimum allowed part size is 5MB,
  85. // and if this value is set to zero, the default value (5MB) for the AWS SDK will be used.
  86. // The minimum allowed value is 5.
  87. // Please note that if the upload bandwidth between the SFTP client and SFTPGo is greater than
  88. // the upload bandwidth between SFTPGo and S3 then the SFTP client have to wait for the upload
  89. // of the last parts to S3 after it ends the file upload to SFTPGo, and it may time out.
  90. // Keep this in mind if you customize these parameters.
  91. UploadPartSize int64 `json:"upload_part_size,omitempty"`
  92. // How many parts are uploaded in parallel
  93. UploadConcurrency int `json:"upload_concurrency,omitempty"`
  94. }
  95. // GCSFsConfig defines the configuration for Google Cloud Storage based filesystem
  96. type GCSFsConfig struct {
  97. Bucket string `json:"bucket,omitempty"`
  98. // KeyPrefix is similar to a chroot directory for local filesystem.
  99. // If specified then the SFTP user will only see objects that starts
  100. // with this prefix and so you can restrict access to a specific
  101. // folder. The prefix, if not empty, must not start with "/" and must
  102. // end with "/".
  103. // If empty the whole bucket contents will be available
  104. KeyPrefix string `json:"key_prefix,omitempty"`
  105. CredentialFile string `json:"-"`
  106. Credentials string `json:"credentials,omitempty"`
  107. AutomaticCredentials int `json:"automatic_credentials,omitempty"`
  108. StorageClass string `json:"storage_class,omitempty"`
  109. }
  110. // PipeWriter defines a wrapper for pipeat.PipeWriterAt.
  111. type PipeWriter struct {
  112. writer *pipeat.PipeWriterAt
  113. err error
  114. done chan bool
  115. }
  116. // NewPipeWriter initializes a new PipeWriter
  117. func NewPipeWriter(w *pipeat.PipeWriterAt) *PipeWriter {
  118. return &PipeWriter{
  119. writer: w,
  120. err: nil,
  121. done: make(chan bool),
  122. }
  123. }
  124. // Close waits for the upload to end, closes the pipeat.PipeWriterAt and returns an error if any.
  125. func (p *PipeWriter) Close() error {
  126. p.writer.Close() //nolint:errcheck // the returned error is always null
  127. <-p.done
  128. return p.err
  129. }
  130. // Done unlocks other goroutines waiting on Close().
  131. // It must be called when the upload ends
  132. func (p *PipeWriter) Done(err error) {
  133. p.err = err
  134. p.done <- true
  135. }
  136. // WriteAt is a wrapper for pipeat WriteAt
  137. func (p *PipeWriter) WriteAt(data []byte, off int64) (int, error) {
  138. return p.writer.WriteAt(data, off)
  139. }
  140. // Write is a wrapper for pipeat Write
  141. func (p *PipeWriter) Write(data []byte) (int, error) {
  142. return p.writer.Write(data)
  143. }
  144. // IsDirectory checks if a path exists and is a directory
  145. func IsDirectory(fs Fs, path string) (bool, error) {
  146. fileInfo, err := fs.Stat(path)
  147. if err != nil {
  148. return false, err
  149. }
  150. return fileInfo.IsDir(), err
  151. }
  152. // IsLocalOsFs returns true if fs is the local filesystem implementation
  153. func IsLocalOsFs(fs Fs) bool {
  154. return fs.Name() == osFsName
  155. }
  156. // ValidateS3FsConfig returns nil if the specified s3 config is valid, otherwise an error
  157. func ValidateS3FsConfig(config *S3FsConfig) error {
  158. if len(config.Bucket) == 0 {
  159. return errors.New("bucket cannot be empty")
  160. }
  161. if len(config.Region) == 0 {
  162. return errors.New("region cannot be empty")
  163. }
  164. if len(config.AccessKey) == 0 && len(config.AccessSecret) > 0 {
  165. return errors.New("access_key cannot be empty with access_secret not empty")
  166. }
  167. if len(config.AccessSecret) == 0 && len(config.AccessKey) > 0 {
  168. return errors.New("access_secret cannot be empty with access_key not empty")
  169. }
  170. if len(config.KeyPrefix) > 0 {
  171. if strings.HasPrefix(config.KeyPrefix, "/") {
  172. return errors.New("key_prefix cannot start with /")
  173. }
  174. config.KeyPrefix = path.Clean(config.KeyPrefix)
  175. if !strings.HasSuffix(config.KeyPrefix, "/") {
  176. config.KeyPrefix += "/"
  177. }
  178. }
  179. if config.UploadPartSize != 0 && config.UploadPartSize < 5 {
  180. return errors.New("upload_part_size cannot be != 0 and lower than 5 (MB)")
  181. }
  182. if config.UploadConcurrency < 0 {
  183. return fmt.Errorf("invalid upload concurrency: %v", config.UploadConcurrency)
  184. }
  185. return nil
  186. }
  187. // ValidateGCSFsConfig returns nil if the specified GCS config is valid, otherwise an error
  188. func ValidateGCSFsConfig(config *GCSFsConfig, credentialsFilePath string) error {
  189. if len(config.Bucket) == 0 {
  190. return errors.New("bucket cannot be empty")
  191. }
  192. if len(config.KeyPrefix) > 0 {
  193. if strings.HasPrefix(config.KeyPrefix, "/") {
  194. return errors.New("key_prefix cannot start with /")
  195. }
  196. config.KeyPrefix = path.Clean(config.KeyPrefix)
  197. if !strings.HasSuffix(config.KeyPrefix, "/") {
  198. config.KeyPrefix += "/"
  199. }
  200. }
  201. if len(config.Credentials) == 0 && config.AutomaticCredentials == 0 {
  202. fi, err := os.Stat(credentialsFilePath)
  203. if err != nil {
  204. return fmt.Errorf("invalid credentials %v", err)
  205. }
  206. if fi.Size() == 0 {
  207. return errors.New("credentials cannot be empty")
  208. }
  209. }
  210. return nil
  211. }
  212. // SetPathPermissions calls fs.Chown.
  213. // It does nothing for local filesystem on windows
  214. func SetPathPermissions(fs Fs, path string, uid int, gid int) {
  215. if IsLocalOsFs(fs) {
  216. if runtime.GOOS == "windows" {
  217. return
  218. }
  219. }
  220. if err := fs.Chown(path, uid, gid); err != nil {
  221. fsLog(fs, logger.LevelWarn, "error chowning path %v: %v", path, err)
  222. }
  223. }
  224. func fsLog(fs Fs, level logger.LogLevel, format string, v ...interface{}) {
  225. logger.Log(level, fs.Name(), fs.ConnectionID(), format, v...)
  226. }