vfs.go 20 KB

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