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