vfs.go 25 KB

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