vfs.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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/pkg/sftp"
  16. "github.com/sftpgo/sdk"
  17. "github.com/sftpgo/sdk/plugin/metadata"
  18. "github.com/drakkan/sftpgo/v2/kms"
  19. "github.com/drakkan/sftpgo/v2/logger"
  20. "github.com/drakkan/sftpgo/v2/plugin"
  21. "github.com/drakkan/sftpgo/v2/util"
  22. )
  23. const dirMimeType = "inode/directory"
  24. var (
  25. validAzAccessTier = []string{"", "Archive", "Hot", "Cool"}
  26. // ErrStorageSizeUnavailable is returned if the storage backend does not support getting the size
  27. ErrStorageSizeUnavailable = errors.New("unable to get available size for this storage backend")
  28. // ErrVfsUnsupported defines the error for an unsupported VFS operation
  29. ErrVfsUnsupported = errors.New("not supported")
  30. credentialsDirPath string
  31. tempPath string
  32. sftpFingerprints []string
  33. )
  34. // SetCredentialsDirPath sets the credentials dir path
  35. func SetCredentialsDirPath(credentialsPath string) {
  36. credentialsDirPath = credentialsPath
  37. }
  38. // GetCredentialsDirPath returns the credentials dir path
  39. func GetCredentialsDirPath() string {
  40. return credentialsDirPath
  41. }
  42. // SetTempPath sets the path for temporary files
  43. func SetTempPath(fsPath string) {
  44. tempPath = fsPath
  45. }
  46. // GetTempPath returns the path for temporary files
  47. func GetTempPath() string {
  48. return tempPath
  49. }
  50. // SetSFTPFingerprints sets the SFTP host key fingerprints
  51. func SetSFTPFingerprints(fp []string) {
  52. sftpFingerprints = fp
  53. }
  54. // Fs defines the interface for filesystem backends
  55. type Fs interface {
  56. Name() string
  57. ConnectionID() string
  58. Stat(name string) (os.FileInfo, error)
  59. Lstat(name string) (os.FileInfo, error)
  60. Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error)
  61. Create(name string, flag int) (File, *PipeWriter, func(), error)
  62. Rename(source, target string) error
  63. Remove(name string, isDir bool) error
  64. Mkdir(name string) error
  65. MkdirAll(name string, uid int, gid int) error
  66. Symlink(source, target string) error
  67. Chown(name string, uid int, gid int) error
  68. Chmod(name string, mode os.FileMode) error
  69. Chtimes(name string, atime, mtime time.Time, isUploading bool) error
  70. Truncate(name string, size int64) error
  71. ReadDir(dirname string) ([]os.FileInfo, error)
  72. Readlink(name string) (string, error)
  73. IsUploadResumeSupported() bool
  74. IsAtomicUploadSupported() bool
  75. CheckRootPath(username string, uid int, gid int) bool
  76. ResolvePath(sftpPath string) (string, error)
  77. IsNotExist(err error) bool
  78. IsPermission(err error) bool
  79. IsNotSupported(err error) bool
  80. ScanRootDirContents() (int, int64, error)
  81. GetDirSize(dirname string) (int, int64, error)
  82. GetAtomicUploadPath(name string) string
  83. GetRelativePath(name string) string
  84. Walk(root string, walkFn filepath.WalkFunc) error
  85. Join(elem ...string) string
  86. HasVirtualFolders() bool
  87. GetMimeType(name string) (string, error)
  88. GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error)
  89. CheckMetadata() error
  90. Close() error
  91. }
  92. // fsMetadataChecker is a Fs that implements the getFileNamesInPrefix method.
  93. // This interface is used to abstract metadata consistency checks
  94. type fsMetadataChecker interface {
  95. Fs
  96. getFileNamesInPrefix(fsPrefix string) (map[string]bool, error)
  97. }
  98. // File defines an interface representing a SFTPGo file
  99. type File interface {
  100. io.Reader
  101. io.Writer
  102. io.Closer
  103. io.ReaderAt
  104. io.WriterAt
  105. io.Seeker
  106. Stat() (os.FileInfo, error)
  107. Name() string
  108. Truncate(size int64) error
  109. }
  110. // QuotaCheckResult defines the result for a quota check
  111. type QuotaCheckResult struct {
  112. HasSpace bool
  113. AllowedSize int64
  114. AllowedFiles int
  115. UsedSize int64
  116. UsedFiles int
  117. QuotaSize int64
  118. QuotaFiles int
  119. }
  120. // GetRemainingSize returns the remaining allowed size
  121. func (q *QuotaCheckResult) GetRemainingSize() int64 {
  122. if q.QuotaSize > 0 {
  123. return q.QuotaSize - q.UsedSize
  124. }
  125. return 0
  126. }
  127. // GetRemainingFiles returns the remaining allowed files
  128. func (q *QuotaCheckResult) GetRemainingFiles() int {
  129. if q.QuotaFiles > 0 {
  130. return q.QuotaFiles - q.UsedFiles
  131. }
  132. return 0
  133. }
  134. // S3FsConfig defines the configuration for S3 based filesystem
  135. type S3FsConfig struct {
  136. sdk.BaseS3FsConfig
  137. AccessSecret *kms.Secret `json:"access_secret,omitempty"`
  138. }
  139. // HideConfidentialData hides confidential data
  140. func (c *S3FsConfig) HideConfidentialData() {
  141. if c.AccessSecret != nil {
  142. c.AccessSecret.Hide()
  143. }
  144. }
  145. func (c *S3FsConfig) isEqual(other *S3FsConfig) bool {
  146. if c.Bucket != other.Bucket {
  147. return false
  148. }
  149. if c.KeyPrefix != other.KeyPrefix {
  150. return false
  151. }
  152. if c.Region != other.Region {
  153. return false
  154. }
  155. if c.AccessKey != other.AccessKey {
  156. return false
  157. }
  158. if c.Endpoint != other.Endpoint {
  159. return false
  160. }
  161. if c.StorageClass != other.StorageClass {
  162. return false
  163. }
  164. if c.ACL != other.ACL {
  165. return false
  166. }
  167. if c.UploadPartSize != other.UploadPartSize {
  168. return false
  169. }
  170. if c.UploadConcurrency != other.UploadConcurrency {
  171. return false
  172. }
  173. if c.DownloadConcurrency != other.DownloadConcurrency {
  174. return false
  175. }
  176. if c.DownloadPartSize != other.DownloadPartSize {
  177. return false
  178. }
  179. if c.DownloadPartMaxTime != other.DownloadPartMaxTime {
  180. return false
  181. }
  182. if c.UploadPartMaxTime != other.UploadPartMaxTime {
  183. return false
  184. }
  185. if c.ForcePathStyle != other.ForcePathStyle {
  186. return false
  187. }
  188. return c.isSecretEqual(other)
  189. }
  190. func (c *S3FsConfig) isSecretEqual(other *S3FsConfig) bool {
  191. if c.AccessSecret == nil {
  192. c.AccessSecret = kms.NewEmptySecret()
  193. }
  194. if other.AccessSecret == nil {
  195. other.AccessSecret = kms.NewEmptySecret()
  196. }
  197. return c.AccessSecret.IsEqual(other.AccessSecret)
  198. }
  199. func (c *S3FsConfig) checkCredentials() error {
  200. if c.AccessKey == "" && !c.AccessSecret.IsEmpty() {
  201. return errors.New("access_key cannot be empty with access_secret not empty")
  202. }
  203. if c.AccessSecret.IsEmpty() && c.AccessKey != "" {
  204. return errors.New("access_secret cannot be empty with access_key not empty")
  205. }
  206. if c.AccessSecret.IsEncrypted() && !c.AccessSecret.IsValid() {
  207. return errors.New("invalid encrypted access_secret")
  208. }
  209. if !c.AccessSecret.IsEmpty() && !c.AccessSecret.IsValidInput() {
  210. return errors.New("invalid access_secret")
  211. }
  212. return nil
  213. }
  214. // EncryptCredentials encrypts access secret if it is in plain text
  215. func (c *S3FsConfig) EncryptCredentials(additionalData string) error {
  216. if c.AccessSecret.IsPlain() {
  217. c.AccessSecret.SetAdditionalData(additionalData)
  218. err := c.AccessSecret.Encrypt()
  219. if err != nil {
  220. return err
  221. }
  222. }
  223. return nil
  224. }
  225. func (c *S3FsConfig) checkPartSizeAndConcurrency() error {
  226. if c.UploadPartSize != 0 && (c.UploadPartSize < 5 || c.UploadPartSize > 5000) {
  227. return errors.New("upload_part_size cannot be != 0, lower than 5 (MB) or greater than 5000 (MB)")
  228. }
  229. if c.UploadConcurrency < 0 || c.UploadConcurrency > 64 {
  230. return fmt.Errorf("invalid upload concurrency: %v", c.UploadConcurrency)
  231. }
  232. if c.DownloadPartSize != 0 && (c.DownloadPartSize < 5 || c.DownloadPartSize > 5000) {
  233. return errors.New("download_part_size cannot be != 0, lower than 5 (MB) or greater than 5000 (MB)")
  234. }
  235. if c.DownloadConcurrency < 0 || c.DownloadConcurrency > 64 {
  236. return fmt.Errorf("invalid download concurrency: %v", c.DownloadConcurrency)
  237. }
  238. return nil
  239. }
  240. // Validate returns an error if the configuration is not valid
  241. func (c *S3FsConfig) Validate() error {
  242. if c.AccessSecret == nil {
  243. c.AccessSecret = kms.NewEmptySecret()
  244. }
  245. if c.Bucket == "" {
  246. return errors.New("bucket cannot be empty")
  247. }
  248. if c.Region == "" {
  249. return errors.New("region cannot be empty")
  250. }
  251. if err := c.checkCredentials(); err != nil {
  252. return err
  253. }
  254. if c.KeyPrefix != "" {
  255. if strings.HasPrefix(c.KeyPrefix, "/") {
  256. return errors.New("key_prefix cannot start with /")
  257. }
  258. c.KeyPrefix = path.Clean(c.KeyPrefix)
  259. if !strings.HasSuffix(c.KeyPrefix, "/") {
  260. c.KeyPrefix += "/"
  261. }
  262. }
  263. c.StorageClass = strings.TrimSpace(c.StorageClass)
  264. c.ACL = strings.TrimSpace(c.ACL)
  265. return c.checkPartSizeAndConcurrency()
  266. }
  267. // GCSFsConfig defines the configuration for Google Cloud Storage based filesystem
  268. type GCSFsConfig struct {
  269. sdk.BaseGCSFsConfig
  270. Credentials *kms.Secret `json:"credentials,omitempty"`
  271. }
  272. // HideConfidentialData hides confidential data
  273. func (c *GCSFsConfig) HideConfidentialData() {
  274. if c.Credentials != nil {
  275. c.Credentials.Hide()
  276. }
  277. }
  278. func (c *GCSFsConfig) isEqual(other *GCSFsConfig) bool {
  279. if c.Bucket != other.Bucket {
  280. return false
  281. }
  282. if c.KeyPrefix != other.KeyPrefix {
  283. return false
  284. }
  285. if c.AutomaticCredentials != other.AutomaticCredentials {
  286. return false
  287. }
  288. if c.StorageClass != other.StorageClass {
  289. return false
  290. }
  291. if c.ACL != other.ACL {
  292. return false
  293. }
  294. if c.Credentials == nil {
  295. c.Credentials = kms.NewEmptySecret()
  296. }
  297. if other.Credentials == nil {
  298. other.Credentials = kms.NewEmptySecret()
  299. }
  300. return c.Credentials.IsEqual(other.Credentials)
  301. }
  302. // Validate returns an error if the configuration is not valid
  303. func (c *GCSFsConfig) Validate(credentialsFilePath string) error {
  304. if c.Credentials == nil || c.AutomaticCredentials == 1 {
  305. c.Credentials = kms.NewEmptySecret()
  306. }
  307. if c.Bucket == "" {
  308. return errors.New("bucket cannot be empty")
  309. }
  310. if c.KeyPrefix != "" {
  311. if strings.HasPrefix(c.KeyPrefix, "/") {
  312. return errors.New("key_prefix cannot start with /")
  313. }
  314. c.KeyPrefix = path.Clean(c.KeyPrefix)
  315. if !strings.HasSuffix(c.KeyPrefix, "/") {
  316. c.KeyPrefix += "/"
  317. }
  318. }
  319. if c.Credentials.IsEncrypted() && !c.Credentials.IsValid() {
  320. return errors.New("invalid encrypted credentials")
  321. }
  322. if c.AutomaticCredentials == 0 && !c.Credentials.IsValidInput() {
  323. fi, err := os.Stat(credentialsFilePath)
  324. if err != nil {
  325. return fmt.Errorf("invalid credentials %v", err)
  326. }
  327. if fi.Size() == 0 {
  328. return errors.New("credentials cannot be empty")
  329. }
  330. }
  331. c.StorageClass = strings.TrimSpace(c.StorageClass)
  332. c.ACL = strings.TrimSpace(c.ACL)
  333. return nil
  334. }
  335. // AzBlobFsConfig defines the configuration for Azure Blob Storage based filesystem
  336. type AzBlobFsConfig struct {
  337. sdk.BaseAzBlobFsConfig
  338. // Storage Account Key leave blank to use SAS URL.
  339. // The access key is stored encrypted based on the kms configuration
  340. AccountKey *kms.Secret `json:"account_key,omitempty"`
  341. // Shared access signature URL, leave blank if using account/key
  342. SASURL *kms.Secret `json:"sas_url,omitempty"`
  343. }
  344. // HideConfidentialData hides confidential data
  345. func (c *AzBlobFsConfig) HideConfidentialData() {
  346. if c.AccountKey != nil {
  347. c.AccountKey.Hide()
  348. }
  349. if c.SASURL != nil {
  350. c.SASURL.Hide()
  351. }
  352. }
  353. func (c *AzBlobFsConfig) isEqual(other *AzBlobFsConfig) bool {
  354. if c.Container != other.Container {
  355. return false
  356. }
  357. if c.AccountName != other.AccountName {
  358. return false
  359. }
  360. if c.Endpoint != other.Endpoint {
  361. return false
  362. }
  363. if c.SASURL.IsEmpty() {
  364. c.SASURL = kms.NewEmptySecret()
  365. }
  366. if other.SASURL.IsEmpty() {
  367. other.SASURL = kms.NewEmptySecret()
  368. }
  369. if !c.SASURL.IsEqual(other.SASURL) {
  370. return false
  371. }
  372. if c.KeyPrefix != other.KeyPrefix {
  373. return false
  374. }
  375. if c.UploadPartSize != other.UploadPartSize {
  376. return false
  377. }
  378. if c.UploadConcurrency != other.UploadConcurrency {
  379. return false
  380. }
  381. if c.UseEmulator != other.UseEmulator {
  382. return false
  383. }
  384. if c.AccessTier != other.AccessTier {
  385. return false
  386. }
  387. if c.AccountKey == nil {
  388. c.AccountKey = kms.NewEmptySecret()
  389. }
  390. if other.AccountKey == nil {
  391. other.AccountKey = kms.NewEmptySecret()
  392. }
  393. return c.AccountKey.IsEqual(other.AccountKey)
  394. }
  395. // EncryptCredentials encrypts access secret if it is in plain text
  396. func (c *AzBlobFsConfig) EncryptCredentials(additionalData string) error {
  397. if c.AccountKey.IsPlain() {
  398. c.AccountKey.SetAdditionalData(additionalData)
  399. if err := c.AccountKey.Encrypt(); err != nil {
  400. return err
  401. }
  402. }
  403. if c.SASURL.IsPlain() {
  404. c.SASURL.SetAdditionalData(additionalData)
  405. if err := c.SASURL.Encrypt(); err != nil {
  406. return err
  407. }
  408. }
  409. return nil
  410. }
  411. func (c *AzBlobFsConfig) checkCredentials() error {
  412. if c.SASURL.IsPlain() {
  413. _, err := url.Parse(c.SASURL.GetPayload())
  414. return err
  415. }
  416. if c.SASURL.IsEncrypted() && !c.SASURL.IsValid() {
  417. return errors.New("invalid encrypted sas_url")
  418. }
  419. if !c.SASURL.IsEmpty() {
  420. return nil
  421. }
  422. if c.AccountName == "" || !c.AccountKey.IsValidInput() {
  423. return errors.New("credentials cannot be empty or invalid")
  424. }
  425. if c.AccountKey.IsEncrypted() && !c.AccountKey.IsValid() {
  426. return errors.New("invalid encrypted account_key")
  427. }
  428. return nil
  429. }
  430. // Validate returns an error if the configuration is not valid
  431. func (c *AzBlobFsConfig) Validate() error {
  432. if c.AccountKey == nil {
  433. c.AccountKey = kms.NewEmptySecret()
  434. }
  435. if c.SASURL == nil {
  436. c.SASURL = kms.NewEmptySecret()
  437. }
  438. // container could be embedded within SAS URL we check this at runtime
  439. if c.SASURL.IsEmpty() && c.Container == "" {
  440. return errors.New("container cannot be empty")
  441. }
  442. if err := c.checkCredentials(); err != nil {
  443. return err
  444. }
  445. if c.KeyPrefix != "" {
  446. if strings.HasPrefix(c.KeyPrefix, "/") {
  447. return errors.New("key_prefix cannot start with /")
  448. }
  449. c.KeyPrefix = path.Clean(c.KeyPrefix)
  450. if !strings.HasSuffix(c.KeyPrefix, "/") {
  451. c.KeyPrefix += "/"
  452. }
  453. }
  454. if c.UploadPartSize < 0 || c.UploadPartSize > 100 {
  455. return fmt.Errorf("invalid upload part size: %v", c.UploadPartSize)
  456. }
  457. if c.UploadConcurrency < 0 || c.UploadConcurrency > 64 {
  458. return fmt.Errorf("invalid upload concurrency: %v", c.UploadConcurrency)
  459. }
  460. if !util.IsStringInSlice(c.AccessTier, validAzAccessTier) {
  461. return fmt.Errorf("invalid access tier %#v, valid values: \"''%v\"", c.AccessTier, strings.Join(validAzAccessTier, ", "))
  462. }
  463. return nil
  464. }
  465. // CryptFsConfig defines the configuration to store local files as encrypted
  466. type CryptFsConfig struct {
  467. Passphrase *kms.Secret `json:"passphrase,omitempty"`
  468. }
  469. // HideConfidentialData hides confidential data
  470. func (c *CryptFsConfig) HideConfidentialData() {
  471. if c.Passphrase != nil {
  472. c.Passphrase.Hide()
  473. }
  474. }
  475. func (c *CryptFsConfig) isEqual(other *CryptFsConfig) bool {
  476. if c.Passphrase == nil {
  477. c.Passphrase = kms.NewEmptySecret()
  478. }
  479. if other.Passphrase == nil {
  480. other.Passphrase = kms.NewEmptySecret()
  481. }
  482. return c.Passphrase.IsEqual(other.Passphrase)
  483. }
  484. // EncryptCredentials encrypts access secret if it is in plain text
  485. func (c *CryptFsConfig) EncryptCredentials(additionalData string) error {
  486. if c.Passphrase.IsPlain() {
  487. c.Passphrase.SetAdditionalData(additionalData)
  488. if err := c.Passphrase.Encrypt(); err != nil {
  489. return err
  490. }
  491. }
  492. return nil
  493. }
  494. // Validate returns an error if the configuration is not valid
  495. func (c *CryptFsConfig) Validate() error {
  496. if c.Passphrase == nil || c.Passphrase.IsEmpty() {
  497. return errors.New("invalid passphrase")
  498. }
  499. if !c.Passphrase.IsValidInput() {
  500. return errors.New("passphrase cannot be empty or invalid")
  501. }
  502. if c.Passphrase.IsEncrypted() && !c.Passphrase.IsValid() {
  503. return errors.New("invalid encrypted passphrase")
  504. }
  505. return nil
  506. }
  507. // PipeWriter defines a wrapper for pipeat.PipeWriterAt.
  508. type PipeWriter struct {
  509. writer *pipeat.PipeWriterAt
  510. err error
  511. done chan bool
  512. }
  513. // NewPipeWriter initializes a new PipeWriter
  514. func NewPipeWriter(w *pipeat.PipeWriterAt) *PipeWriter {
  515. return &PipeWriter{
  516. writer: w,
  517. err: nil,
  518. done: make(chan bool),
  519. }
  520. }
  521. // Close waits for the upload to end, closes the pipeat.PipeWriterAt and returns an error if any.
  522. func (p *PipeWriter) Close() error {
  523. p.writer.Close() //nolint:errcheck // the returned error is always null
  524. <-p.done
  525. return p.err
  526. }
  527. // Done unlocks other goroutines waiting on Close().
  528. // It must be called when the upload ends
  529. func (p *PipeWriter) Done(err error) {
  530. p.err = err
  531. p.done <- true
  532. }
  533. // WriteAt is a wrapper for pipeat WriteAt
  534. func (p *PipeWriter) WriteAt(data []byte, off int64) (int, error) {
  535. return p.writer.WriteAt(data, off)
  536. }
  537. // Write is a wrapper for pipeat Write
  538. func (p *PipeWriter) Write(data []byte) (int, error) {
  539. return p.writer.Write(data)
  540. }
  541. // IsDirectory checks if a path exists and is a directory
  542. func IsDirectory(fs Fs, path string) (bool, error) {
  543. fileInfo, err := fs.Stat(path)
  544. if err != nil {
  545. return false, err
  546. }
  547. return fileInfo.IsDir(), err
  548. }
  549. // IsLocalOsFs returns true if fs is a local filesystem implementation
  550. func IsLocalOsFs(fs Fs) bool {
  551. return fs.Name() == osFsName
  552. }
  553. // IsCryptOsFs returns true if fs is an encrypted local filesystem implementation
  554. func IsCryptOsFs(fs Fs) bool {
  555. return fs.Name() == cryptFsName
  556. }
  557. // IsSFTPFs returns true if fs is an SFTP filesystem
  558. func IsSFTPFs(fs Fs) bool {
  559. return strings.HasPrefix(fs.Name(), sftpFsName)
  560. }
  561. // IsBufferedSFTPFs returns true if this is a buffered SFTP filesystem
  562. func IsBufferedSFTPFs(fs Fs) bool {
  563. if !IsSFTPFs(fs) {
  564. return false
  565. }
  566. return !fs.IsUploadResumeSupported()
  567. }
  568. // IsLocalOrUnbufferedSFTPFs returns true if fs is local or SFTP with no buffer
  569. func IsLocalOrUnbufferedSFTPFs(fs Fs) bool {
  570. if IsLocalOsFs(fs) {
  571. return true
  572. }
  573. if IsSFTPFs(fs) {
  574. return fs.IsUploadResumeSupported()
  575. }
  576. return false
  577. }
  578. // IsLocalOrSFTPFs returns true if fs is local or SFTP
  579. func IsLocalOrSFTPFs(fs Fs) bool {
  580. return IsLocalOsFs(fs) || IsSFTPFs(fs)
  581. }
  582. // HasOpenRWSupport returns true if the fs can open a file
  583. // for reading and writing at the same time
  584. func HasOpenRWSupport(fs Fs) bool {
  585. if IsLocalOsFs(fs) {
  586. return true
  587. }
  588. if IsSFTPFs(fs) && fs.IsUploadResumeSupported() {
  589. return true
  590. }
  591. return false
  592. }
  593. // IsLocalOrCryptoFs returns true if fs is local or local encrypted
  594. func IsLocalOrCryptoFs(fs Fs) bool {
  595. return IsLocalOsFs(fs) || IsCryptOsFs(fs)
  596. }
  597. // SetPathPermissions calls fs.Chown.
  598. // It does nothing for local filesystem on windows
  599. func SetPathPermissions(fs Fs, path string, uid int, gid int) {
  600. if uid == -1 && gid == -1 {
  601. return
  602. }
  603. if IsLocalOsFs(fs) {
  604. if runtime.GOOS == "windows" {
  605. return
  606. }
  607. }
  608. if err := fs.Chown(path, uid, gid); err != nil {
  609. fsLog(fs, logger.LevelWarn, "error chowning path %v: %v", path, err)
  610. }
  611. }
  612. func updateFileInfoModTime(storageID, objectPath string, info *FileInfo) (*FileInfo, error) {
  613. if !plugin.Handler.HasMetadater() {
  614. return info, nil
  615. }
  616. if info.IsDir() {
  617. return info, nil
  618. }
  619. mTime, err := plugin.Handler.GetModificationTime(storageID, ensureAbsPath(objectPath), info.IsDir())
  620. if errors.Is(err, metadata.ErrNoSuchObject) {
  621. return info, nil
  622. }
  623. if err != nil {
  624. return info, err
  625. }
  626. info.modTime = util.GetTimeFromMsecSinceEpoch(mTime)
  627. return info, nil
  628. }
  629. func getFolderModTimes(storageID, dirName string) (map[string]int64, error) {
  630. var err error
  631. modTimes := make(map[string]int64)
  632. if plugin.Handler.HasMetadater() {
  633. modTimes, err = plugin.Handler.GetModificationTimes(storageID, ensureAbsPath(dirName))
  634. if err != nil && !errors.Is(err, metadata.ErrNoSuchObject) {
  635. return modTimes, err
  636. }
  637. }
  638. return modTimes, nil
  639. }
  640. func ensureAbsPath(name string) string {
  641. if path.IsAbs(name) {
  642. return name
  643. }
  644. return path.Join("/", name)
  645. }
  646. func fsMetadataCheck(fs fsMetadataChecker, storageID, keyPrefix string) error {
  647. if !plugin.Handler.HasMetadater() {
  648. return nil
  649. }
  650. limit := 100
  651. from := ""
  652. for {
  653. metadataFolders, err := plugin.Handler.GetMetadataFolders(storageID, from, limit)
  654. if err != nil {
  655. fsLog(fs, logger.LevelError, "unable to get folders: %v", err)
  656. return err
  657. }
  658. for _, folder := range metadataFolders {
  659. from = folder
  660. fsPrefix := folder
  661. if !strings.HasSuffix(folder, "/") {
  662. fsPrefix += "/"
  663. }
  664. if keyPrefix != "" {
  665. if !strings.HasPrefix(fsPrefix, "/"+keyPrefix) {
  666. fsLog(fs, logger.LevelDebug, "skip metadata check for folder %#v outside prefix %#v",
  667. folder, keyPrefix)
  668. continue
  669. }
  670. }
  671. fsLog(fs, logger.LevelDebug, "check metadata for folder %#v", folder)
  672. metadataValues, err := plugin.Handler.GetModificationTimes(storageID, folder)
  673. if err != nil {
  674. fsLog(fs, logger.LevelError, "unable to get modification times for folder %#v: %v", folder, err)
  675. return err
  676. }
  677. if len(metadataValues) == 0 {
  678. fsLog(fs, logger.LevelDebug, "no metadata for folder %#v", folder)
  679. continue
  680. }
  681. fileNames, err := fs.getFileNamesInPrefix(fsPrefix)
  682. if err != nil {
  683. fsLog(fs, logger.LevelError, "unable to get content for prefix %#v: %v", fsPrefix, err)
  684. return err
  685. }
  686. // now check if we have metadata for a missing object
  687. for k := range metadataValues {
  688. if _, ok := fileNames[k]; !ok {
  689. filePath := ensureAbsPath(path.Join(folder, k))
  690. if err = plugin.Handler.RemoveMetadata(storageID, filePath); err != nil {
  691. fsLog(fs, logger.LevelError, "unable to remove metadata for missing file %#v: %v", filePath, err)
  692. } else {
  693. fsLog(fs, logger.LevelDebug, "metadata removed for missing file %#v", filePath)
  694. }
  695. }
  696. }
  697. }
  698. if len(metadataFolders) < limit {
  699. return nil
  700. }
  701. }
  702. }
  703. func fsLog(fs Fs, level logger.LogLevel, format string, v ...interface{}) {
  704. logger.Log(level, fs.Name(), fs.ConnectionID(), format, v...)
  705. }