vfs.go 24 KB

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