vfs.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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/drakkan/sftpgo/v2/kms"
  17. "github.com/drakkan/sftpgo/v2/logger"
  18. "github.com/drakkan/sftpgo/v2/sdk"
  19. "github.com/drakkan/sftpgo/v2/sdk/plugin"
  20. "github.com/drakkan/sftpgo/v2/sdk/plugin/metadata"
  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.S3FsConfig
  137. }
  138. // HideConfidentialData hides confidential data
  139. func (c *S3FsConfig) HideConfidentialData() {
  140. if c.AccessSecret != nil {
  141. c.AccessSecret.Hide()
  142. }
  143. }
  144. func (c *S3FsConfig) isEqual(other *S3FsConfig) bool {
  145. if c.Bucket != other.Bucket {
  146. return false
  147. }
  148. if c.KeyPrefix != other.KeyPrefix {
  149. return false
  150. }
  151. if c.Region != other.Region {
  152. return false
  153. }
  154. if c.AccessKey != other.AccessKey {
  155. return false
  156. }
  157. if c.Endpoint != other.Endpoint {
  158. return false
  159. }
  160. if c.StorageClass != other.StorageClass {
  161. return false
  162. }
  163. if c.ACL != other.ACL {
  164. return false
  165. }
  166. if c.UploadPartSize != other.UploadPartSize {
  167. return false
  168. }
  169. if c.UploadConcurrency != other.UploadConcurrency {
  170. return false
  171. }
  172. if c.DownloadConcurrency != other.DownloadConcurrency {
  173. return false
  174. }
  175. if c.DownloadPartSize != other.DownloadPartSize {
  176. return false
  177. }
  178. if c.DownloadPartMaxTime != other.DownloadPartMaxTime {
  179. return false
  180. }
  181. if c.ForcePathStyle != other.ForcePathStyle {
  182. return false
  183. }
  184. return c.isSecretEqual(other)
  185. }
  186. func (c *S3FsConfig) isSecretEqual(other *S3FsConfig) bool {
  187. if c.AccessSecret == nil {
  188. c.AccessSecret = kms.NewEmptySecret()
  189. }
  190. if other.AccessSecret == nil {
  191. other.AccessSecret = kms.NewEmptySecret()
  192. }
  193. return c.AccessSecret.IsEqual(other.AccessSecret)
  194. }
  195. func (c *S3FsConfig) checkCredentials() error {
  196. if c.AccessKey == "" && !c.AccessSecret.IsEmpty() {
  197. return errors.New("access_key cannot be empty with access_secret not empty")
  198. }
  199. if c.AccessSecret.IsEmpty() && c.AccessKey != "" {
  200. return errors.New("access_secret cannot be empty with access_key not empty")
  201. }
  202. if c.AccessSecret.IsEncrypted() && !c.AccessSecret.IsValid() {
  203. return errors.New("invalid encrypted access_secret")
  204. }
  205. if !c.AccessSecret.IsEmpty() && !c.AccessSecret.IsValidInput() {
  206. return errors.New("invalid access_secret")
  207. }
  208. return nil
  209. }
  210. // EncryptCredentials encrypts access secret if it is in plain text
  211. func (c *S3FsConfig) EncryptCredentials(additionalData string) error {
  212. if c.AccessSecret.IsPlain() {
  213. c.AccessSecret.SetAdditionalData(additionalData)
  214. err := c.AccessSecret.Encrypt()
  215. if err != nil {
  216. return err
  217. }
  218. }
  219. return nil
  220. }
  221. func (c *S3FsConfig) checkPartSizeAndConcurrency() error {
  222. if c.UploadPartSize != 0 && (c.UploadPartSize < 5 || c.UploadPartSize > 5000) {
  223. return errors.New("upload_part_size cannot be != 0, lower than 5 (MB) or greater than 5000 (MB)")
  224. }
  225. if c.UploadConcurrency < 0 || c.UploadConcurrency > 64 {
  226. return fmt.Errorf("invalid upload concurrency: %v", c.UploadConcurrency)
  227. }
  228. if c.DownloadPartSize != 0 && (c.DownloadPartSize < 5 || c.DownloadPartSize > 5000) {
  229. return errors.New("download_part_size cannot be != 0, lower than 5 (MB) or greater than 5000 (MB)")
  230. }
  231. if c.DownloadConcurrency < 0 || c.DownloadConcurrency > 64 {
  232. return fmt.Errorf("invalid download concurrency: %v", c.DownloadConcurrency)
  233. }
  234. return nil
  235. }
  236. // Validate returns an error if the configuration is not valid
  237. func (c *S3FsConfig) Validate() error {
  238. if c.AccessSecret == nil {
  239. c.AccessSecret = kms.NewEmptySecret()
  240. }
  241. if c.Bucket == "" {
  242. return errors.New("bucket cannot be empty")
  243. }
  244. if c.Region == "" {
  245. return errors.New("region cannot be empty")
  246. }
  247. if err := c.checkCredentials(); err != nil {
  248. return err
  249. }
  250. if c.KeyPrefix != "" {
  251. if strings.HasPrefix(c.KeyPrefix, "/") {
  252. return errors.New("key_prefix cannot start with /")
  253. }
  254. c.KeyPrefix = path.Clean(c.KeyPrefix)
  255. if !strings.HasSuffix(c.KeyPrefix, "/") {
  256. c.KeyPrefix += "/"
  257. }
  258. }
  259. c.StorageClass = strings.TrimSpace(c.StorageClass)
  260. c.ACL = strings.TrimSpace(c.ACL)
  261. return c.checkPartSizeAndConcurrency()
  262. }
  263. // GCSFsConfig defines the configuration for Google Cloud Storage based filesystem
  264. type GCSFsConfig struct {
  265. sdk.GCSFsConfig
  266. }
  267. // HideConfidentialData hides confidential data
  268. func (c *GCSFsConfig) HideConfidentialData() {
  269. if c.Credentials != nil {
  270. c.Credentials.Hide()
  271. }
  272. }
  273. func (c *GCSFsConfig) isEqual(other *GCSFsConfig) bool {
  274. if c.Bucket != other.Bucket {
  275. return false
  276. }
  277. if c.KeyPrefix != other.KeyPrefix {
  278. return false
  279. }
  280. if c.AutomaticCredentials != other.AutomaticCredentials {
  281. return false
  282. }
  283. if c.StorageClass != other.StorageClass {
  284. return false
  285. }
  286. if c.ACL != other.ACL {
  287. return false
  288. }
  289. if c.Credentials == nil {
  290. c.Credentials = kms.NewEmptySecret()
  291. }
  292. if other.Credentials == nil {
  293. other.Credentials = kms.NewEmptySecret()
  294. }
  295. return c.Credentials.IsEqual(other.Credentials)
  296. }
  297. // Validate returns an error if the configuration is not valid
  298. func (c *GCSFsConfig) Validate(credentialsFilePath string) error {
  299. if c.Credentials == nil || c.AutomaticCredentials == 1 {
  300. c.Credentials = kms.NewEmptySecret()
  301. }
  302. if c.Bucket == "" {
  303. return errors.New("bucket cannot be empty")
  304. }
  305. if c.KeyPrefix != "" {
  306. if strings.HasPrefix(c.KeyPrefix, "/") {
  307. return errors.New("key_prefix cannot start with /")
  308. }
  309. c.KeyPrefix = path.Clean(c.KeyPrefix)
  310. if !strings.HasSuffix(c.KeyPrefix, "/") {
  311. c.KeyPrefix += "/"
  312. }
  313. }
  314. if c.Credentials.IsEncrypted() && !c.Credentials.IsValid() {
  315. return errors.New("invalid encrypted credentials")
  316. }
  317. if c.AutomaticCredentials == 0 && !c.Credentials.IsValidInput() {
  318. fi, err := os.Stat(credentialsFilePath)
  319. if err != nil {
  320. return fmt.Errorf("invalid credentials %v", err)
  321. }
  322. if fi.Size() == 0 {
  323. return errors.New("credentials cannot be empty")
  324. }
  325. }
  326. c.StorageClass = strings.TrimSpace(c.StorageClass)
  327. c.ACL = strings.TrimSpace(c.ACL)
  328. return nil
  329. }
  330. // AzBlobFsConfig defines the configuration for Azure Blob Storage based filesystem
  331. type AzBlobFsConfig struct {
  332. sdk.AzBlobFsConfig
  333. }
  334. // HideConfidentialData hides confidential data
  335. func (c *AzBlobFsConfig) HideConfidentialData() {
  336. if c.AccountKey != nil {
  337. c.AccountKey.Hide()
  338. }
  339. if c.SASURL != nil {
  340. c.SASURL.Hide()
  341. }
  342. }
  343. func (c *AzBlobFsConfig) isEqual(other *AzBlobFsConfig) bool {
  344. if c.Container != other.Container {
  345. return false
  346. }
  347. if c.AccountName != other.AccountName {
  348. return false
  349. }
  350. if c.Endpoint != other.Endpoint {
  351. return false
  352. }
  353. if c.SASURL.IsEmpty() {
  354. c.SASURL = kms.NewEmptySecret()
  355. }
  356. if other.SASURL.IsEmpty() {
  357. other.SASURL = kms.NewEmptySecret()
  358. }
  359. if !c.SASURL.IsEqual(other.SASURL) {
  360. return false
  361. }
  362. if c.KeyPrefix != other.KeyPrefix {
  363. return false
  364. }
  365. if c.UploadPartSize != other.UploadPartSize {
  366. return false
  367. }
  368. if c.UploadConcurrency != other.UploadConcurrency {
  369. return false
  370. }
  371. if c.UseEmulator != other.UseEmulator {
  372. return false
  373. }
  374. if c.AccessTier != other.AccessTier {
  375. return false
  376. }
  377. if c.AccountKey == nil {
  378. c.AccountKey = kms.NewEmptySecret()
  379. }
  380. if other.AccountKey == nil {
  381. other.AccountKey = kms.NewEmptySecret()
  382. }
  383. return c.AccountKey.IsEqual(other.AccountKey)
  384. }
  385. // EncryptCredentials encrypts access secret if it is in plain text
  386. func (c *AzBlobFsConfig) EncryptCredentials(additionalData string) error {
  387. if c.AccountKey.IsPlain() {
  388. c.AccountKey.SetAdditionalData(additionalData)
  389. if err := c.AccountKey.Encrypt(); err != nil {
  390. return err
  391. }
  392. }
  393. if c.SASURL.IsPlain() {
  394. c.SASURL.SetAdditionalData(additionalData)
  395. if err := c.SASURL.Encrypt(); err != nil {
  396. return err
  397. }
  398. }
  399. return nil
  400. }
  401. func (c *AzBlobFsConfig) checkCredentials() error {
  402. if c.SASURL.IsPlain() {
  403. _, err := url.Parse(c.SASURL.GetPayload())
  404. return err
  405. }
  406. if c.SASURL.IsEncrypted() && !c.SASURL.IsValid() {
  407. return errors.New("invalid encrypted sas_url")
  408. }
  409. if !c.SASURL.IsEmpty() {
  410. return nil
  411. }
  412. if c.AccountName == "" || !c.AccountKey.IsValidInput() {
  413. return errors.New("credentials cannot be empty or invalid")
  414. }
  415. if c.AccountKey.IsEncrypted() && !c.AccountKey.IsValid() {
  416. return errors.New("invalid encrypted account_key")
  417. }
  418. return nil
  419. }
  420. // Validate returns an error if the configuration is not valid
  421. func (c *AzBlobFsConfig) Validate() error {
  422. if c.AccountKey == nil {
  423. c.AccountKey = kms.NewEmptySecret()
  424. }
  425. if c.SASURL == nil {
  426. c.SASURL = kms.NewEmptySecret()
  427. }
  428. // container could be embedded within SAS URL we check this at runtime
  429. if c.SASURL.IsEmpty() && c.Container == "" {
  430. return errors.New("container cannot be empty")
  431. }
  432. if err := c.checkCredentials(); err != nil {
  433. return err
  434. }
  435. if c.KeyPrefix != "" {
  436. if strings.HasPrefix(c.KeyPrefix, "/") {
  437. return errors.New("key_prefix cannot start with /")
  438. }
  439. c.KeyPrefix = path.Clean(c.KeyPrefix)
  440. if !strings.HasSuffix(c.KeyPrefix, "/") {
  441. c.KeyPrefix += "/"
  442. }
  443. }
  444. if c.UploadPartSize < 0 || c.UploadPartSize > 100 {
  445. return fmt.Errorf("invalid upload part size: %v", c.UploadPartSize)
  446. }
  447. if c.UploadConcurrency < 0 || c.UploadConcurrency > 64 {
  448. return fmt.Errorf("invalid upload concurrency: %v", c.UploadConcurrency)
  449. }
  450. if !util.IsStringInSlice(c.AccessTier, validAzAccessTier) {
  451. return fmt.Errorf("invalid access tier %#v, valid values: \"''%v\"", c.AccessTier, strings.Join(validAzAccessTier, ", "))
  452. }
  453. return nil
  454. }
  455. // CryptFsConfig defines the configuration to store local files as encrypted
  456. type CryptFsConfig struct {
  457. sdk.CryptFsConfig
  458. }
  459. // HideConfidentialData hides confidential data
  460. func (c *CryptFsConfig) HideConfidentialData() {
  461. if c.Passphrase != nil {
  462. c.Passphrase.Hide()
  463. }
  464. }
  465. func (c *CryptFsConfig) isEqual(other *CryptFsConfig) bool {
  466. if c.Passphrase == nil {
  467. c.Passphrase = kms.NewEmptySecret()
  468. }
  469. if other.Passphrase == nil {
  470. other.Passphrase = kms.NewEmptySecret()
  471. }
  472. return c.Passphrase.IsEqual(other.Passphrase)
  473. }
  474. // EncryptCredentials encrypts access secret if it is in plain text
  475. func (c *CryptFsConfig) EncryptCredentials(additionalData string) error {
  476. if c.Passphrase.IsPlain() {
  477. c.Passphrase.SetAdditionalData(additionalData)
  478. if err := c.Passphrase.Encrypt(); err != nil {
  479. return err
  480. }
  481. }
  482. return nil
  483. }
  484. // Validate returns an error if the configuration is not valid
  485. func (c *CryptFsConfig) Validate() error {
  486. if c.Passphrase == nil || c.Passphrase.IsEmpty() {
  487. return errors.New("invalid passphrase")
  488. }
  489. if !c.Passphrase.IsValidInput() {
  490. return errors.New("passphrase cannot be empty or invalid")
  491. }
  492. if c.Passphrase.IsEncrypted() && !c.Passphrase.IsValid() {
  493. return errors.New("invalid encrypted passphrase")
  494. }
  495. return nil
  496. }
  497. // PipeWriter defines a wrapper for pipeat.PipeWriterAt.
  498. type PipeWriter struct {
  499. writer *pipeat.PipeWriterAt
  500. err error
  501. done chan bool
  502. }
  503. // NewPipeWriter initializes a new PipeWriter
  504. func NewPipeWriter(w *pipeat.PipeWriterAt) *PipeWriter {
  505. return &PipeWriter{
  506. writer: w,
  507. err: nil,
  508. done: make(chan bool),
  509. }
  510. }
  511. // Close waits for the upload to end, closes the pipeat.PipeWriterAt and returns an error if any.
  512. func (p *PipeWriter) Close() error {
  513. p.writer.Close() //nolint:errcheck // the returned error is always null
  514. <-p.done
  515. return p.err
  516. }
  517. // Done unlocks other goroutines waiting on Close().
  518. // It must be called when the upload ends
  519. func (p *PipeWriter) Done(err error) {
  520. p.err = err
  521. p.done <- true
  522. }
  523. // WriteAt is a wrapper for pipeat WriteAt
  524. func (p *PipeWriter) WriteAt(data []byte, off int64) (int, error) {
  525. return p.writer.WriteAt(data, off)
  526. }
  527. // Write is a wrapper for pipeat Write
  528. func (p *PipeWriter) Write(data []byte) (int, error) {
  529. return p.writer.Write(data)
  530. }
  531. // IsDirectory checks if a path exists and is a directory
  532. func IsDirectory(fs Fs, path string) (bool, error) {
  533. fileInfo, err := fs.Stat(path)
  534. if err != nil {
  535. return false, err
  536. }
  537. return fileInfo.IsDir(), err
  538. }
  539. // IsLocalOsFs returns true if fs is a local filesystem implementation
  540. func IsLocalOsFs(fs Fs) bool {
  541. return fs.Name() == osFsName
  542. }
  543. // IsCryptOsFs returns true if fs is an encrypted local filesystem implementation
  544. func IsCryptOsFs(fs Fs) bool {
  545. return fs.Name() == cryptFsName
  546. }
  547. // IsSFTPFs returns true if fs is an SFTP filesystem
  548. func IsSFTPFs(fs Fs) bool {
  549. return strings.HasPrefix(fs.Name(), sftpFsName)
  550. }
  551. // IsBufferedSFTPFs returns true if this is a buffered SFTP filesystem
  552. func IsBufferedSFTPFs(fs Fs) bool {
  553. if !IsSFTPFs(fs) {
  554. return false
  555. }
  556. return !fs.IsUploadResumeSupported()
  557. }
  558. // IsLocalOrUnbufferedSFTPFs returns true if fs is local or SFTP with no buffer
  559. func IsLocalOrUnbufferedSFTPFs(fs Fs) bool {
  560. if IsLocalOsFs(fs) {
  561. return true
  562. }
  563. if IsSFTPFs(fs) {
  564. return fs.IsUploadResumeSupported()
  565. }
  566. return false
  567. }
  568. // IsLocalOrSFTPFs returns true if fs is local or SFTP
  569. func IsLocalOrSFTPFs(fs Fs) bool {
  570. return IsLocalOsFs(fs) || IsSFTPFs(fs)
  571. }
  572. // HasOpenRWSupport returns true if the fs can open a file
  573. // for reading and writing at the same time
  574. func HasOpenRWSupport(fs Fs) bool {
  575. if IsLocalOsFs(fs) {
  576. return true
  577. }
  578. if IsSFTPFs(fs) && fs.IsUploadResumeSupported() {
  579. return true
  580. }
  581. return false
  582. }
  583. // IsLocalOrCryptoFs returns true if fs is local or local encrypted
  584. func IsLocalOrCryptoFs(fs Fs) bool {
  585. return IsLocalOsFs(fs) || IsCryptOsFs(fs)
  586. }
  587. // SetPathPermissions calls fs.Chown.
  588. // It does nothing for local filesystem on windows
  589. func SetPathPermissions(fs Fs, path string, uid int, gid int) {
  590. if uid == -1 && gid == -1 {
  591. return
  592. }
  593. if IsLocalOsFs(fs) {
  594. if runtime.GOOS == "windows" {
  595. return
  596. }
  597. }
  598. if err := fs.Chown(path, uid, gid); err != nil {
  599. fsLog(fs, logger.LevelWarn, "error chowning path %v: %v", path, err)
  600. }
  601. }
  602. func updateFileInfoModTime(storageID, objectPath string, info *FileInfo) (*FileInfo, error) {
  603. if !plugin.Handler.HasMetadater() {
  604. return info, nil
  605. }
  606. if info.IsDir() {
  607. return info, nil
  608. }
  609. mTime, err := plugin.Handler.GetModificationTime(storageID, ensureAbsPath(objectPath), info.IsDir())
  610. if errors.Is(err, metadata.ErrNoSuchObject) {
  611. return info, nil
  612. }
  613. if err != nil {
  614. return info, err
  615. }
  616. info.modTime = util.GetTimeFromMsecSinceEpoch(mTime)
  617. return info, nil
  618. }
  619. func getFolderModTimes(storageID, dirName string) (map[string]int64, error) {
  620. var err error
  621. modTimes := make(map[string]int64)
  622. if plugin.Handler.HasMetadater() {
  623. modTimes, err = plugin.Handler.GetModificationTimes(storageID, ensureAbsPath(dirName))
  624. if err != nil && !errors.Is(err, metadata.ErrNoSuchObject) {
  625. return modTimes, err
  626. }
  627. }
  628. return modTimes, nil
  629. }
  630. func ensureAbsPath(name string) string {
  631. if path.IsAbs(name) {
  632. return name
  633. }
  634. return path.Join("/", name)
  635. }
  636. func fsMetadataCheck(fs fsMetadataChecker, storageID, keyPrefix string) error {
  637. if !plugin.Handler.HasMetadater() {
  638. return nil
  639. }
  640. limit := 100
  641. from := ""
  642. for {
  643. metadataFolders, err := plugin.Handler.GetMetadataFolders(storageID, from, limit)
  644. if err != nil {
  645. fsLog(fs, logger.LevelError, "unable to get folders: %v", err)
  646. return err
  647. }
  648. for _, folder := range metadataFolders {
  649. from = folder
  650. fsPrefix := folder
  651. if !strings.HasSuffix(folder, "/") {
  652. fsPrefix += "/"
  653. }
  654. if keyPrefix != "" {
  655. if !strings.HasPrefix(fsPrefix, "/"+keyPrefix) {
  656. fsLog(fs, logger.LevelDebug, "skip metadata check for folder %#v outside prefix %#v",
  657. folder, keyPrefix)
  658. continue
  659. }
  660. }
  661. fsLog(fs, logger.LevelDebug, "check metadata for folder %#v", folder)
  662. metadataValues, err := plugin.Handler.GetModificationTimes(storageID, folder)
  663. if err != nil {
  664. fsLog(fs, logger.LevelError, "unable to get modification times for folder %#v: %v", folder, err)
  665. return err
  666. }
  667. if len(metadataValues) == 0 {
  668. fsLog(fs, logger.LevelDebug, "no metadata for folder %#v", folder)
  669. continue
  670. }
  671. fileNames, err := fs.getFileNamesInPrefix(fsPrefix)
  672. if err != nil {
  673. fsLog(fs, logger.LevelError, "unable to get content for prefix %#v: %v", fsPrefix, err)
  674. return err
  675. }
  676. // now check if we have metadata for a missing object
  677. for k := range metadataValues {
  678. if _, ok := fileNames[k]; !ok {
  679. filePath := ensureAbsPath(path.Join(folder, k))
  680. if err = plugin.Handler.RemoveMetadata(storageID, filePath); err != nil {
  681. fsLog(fs, logger.LevelError, "unable to remove metadata for missing file %#v: %v", filePath, err)
  682. } else {
  683. fsLog(fs, logger.LevelDebug, "metadata removed for missing file %#v", filePath)
  684. }
  685. }
  686. }
  687. }
  688. if len(metadataFolders) < limit {
  689. return nil
  690. }
  691. }
  692. }
  693. func fsLog(fs Fs, level logger.LogLevel, format string, v ...interface{}) {
  694. logger.Log(level, fs.Name(), fs.ConnectionID(), format, v...)
  695. }