vfs.go 8.1 KB

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