vfs.go 23 KB

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