s3fs.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. //go:build !nos3
  15. // +build !nos3
  16. package vfs
  17. import (
  18. "context"
  19. "errors"
  20. "fmt"
  21. "mime"
  22. "net"
  23. "net/http"
  24. "net/url"
  25. "os"
  26. "path"
  27. "path/filepath"
  28. "sort"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "github.com/aws/aws-sdk-go-v2/aws"
  34. awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
  35. "github.com/aws/aws-sdk-go-v2/config"
  36. "github.com/aws/aws-sdk-go-v2/credentials"
  37. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  38. "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
  39. "github.com/aws/aws-sdk-go-v2/service/s3"
  40. "github.com/aws/aws-sdk-go-v2/service/s3/types"
  41. "github.com/aws/aws-sdk-go-v2/service/sts"
  42. "github.com/eikenb/pipeat"
  43. "github.com/pkg/sftp"
  44. "github.com/drakkan/sftpgo/v2/internal/logger"
  45. "github.com/drakkan/sftpgo/v2/internal/metric"
  46. "github.com/drakkan/sftpgo/v2/internal/plugin"
  47. "github.com/drakkan/sftpgo/v2/internal/util"
  48. "github.com/drakkan/sftpgo/v2/internal/version"
  49. )
  50. const (
  51. // using this mime type for directories improves compatibility with s3fs-fuse
  52. s3DirMimeType = "application/x-directory"
  53. s3TransferBufferSize = 256 * 1024
  54. )
  55. var (
  56. s3DirMimeTypes = []string{s3DirMimeType, "httpd/unix-directory"}
  57. )
  58. // S3Fs is a Fs implementation for AWS S3 compatible object storages
  59. type S3Fs struct {
  60. connectionID string
  61. localTempDir string
  62. // if not empty this fs is mouted as virtual folder in the specified path
  63. mountPath string
  64. config *S3FsConfig
  65. svc *s3.Client
  66. ctxTimeout time.Duration
  67. }
  68. func init() {
  69. version.AddFeature("+s3")
  70. }
  71. // NewS3Fs returns an S3Fs object that allows to interact with an s3 compatible
  72. // object storage
  73. func NewS3Fs(connectionID, localTempDir, mountPath string, s3Config S3FsConfig) (Fs, error) {
  74. if localTempDir == "" {
  75. if tempPath != "" {
  76. localTempDir = tempPath
  77. } else {
  78. localTempDir = filepath.Clean(os.TempDir())
  79. }
  80. }
  81. fs := &S3Fs{
  82. connectionID: connectionID,
  83. localTempDir: localTempDir,
  84. mountPath: getMountPath(mountPath),
  85. config: &s3Config,
  86. ctxTimeout: 30 * time.Second,
  87. }
  88. if err := fs.config.validate(); err != nil {
  89. return fs, err
  90. }
  91. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  92. defer cancel()
  93. awsConfig, err := config.LoadDefaultConfig(ctx, config.WithHTTPClient(getAWSHTTPClient(0, 30*time.Second)))
  94. if err != nil {
  95. return fs, fmt.Errorf("unable to get AWS config: %w", err)
  96. }
  97. if fs.config.Region != "" {
  98. awsConfig.Region = fs.config.Region
  99. }
  100. if !fs.config.AccessSecret.IsEmpty() {
  101. if err := fs.config.AccessSecret.TryDecrypt(); err != nil {
  102. return fs, err
  103. }
  104. awsConfig.Credentials = aws.NewCredentialsCache(
  105. credentials.NewStaticCredentialsProvider(fs.config.AccessKey, fs.config.AccessSecret.GetPayload(), ""))
  106. }
  107. if fs.config.Endpoint != "" {
  108. endpointResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...any) (aws.Endpoint, error) {
  109. return aws.Endpoint{
  110. URL: fs.config.Endpoint,
  111. HostnameImmutable: fs.config.ForcePathStyle,
  112. PartitionID: "aws",
  113. SigningRegion: fs.config.Region,
  114. Source: aws.EndpointSourceCustom,
  115. }, nil
  116. })
  117. awsConfig.EndpointResolverWithOptions = endpointResolver
  118. }
  119. fs.setConfigDefaults()
  120. if fs.config.RoleARN != "" {
  121. client := sts.NewFromConfig(awsConfig)
  122. creds := stscreds.NewAssumeRoleProvider(client, fs.config.RoleARN)
  123. awsConfig.Credentials = creds
  124. }
  125. fs.svc = s3.NewFromConfig(awsConfig, func(o *s3.Options) {
  126. o.UsePathStyle = fs.config.ForcePathStyle
  127. })
  128. return fs, nil
  129. }
  130. // Name returns the name for the Fs implementation
  131. func (fs *S3Fs) Name() string {
  132. return fmt.Sprintf("%s bucket %q", s3fsName, fs.config.Bucket)
  133. }
  134. // ConnectionID returns the connection ID associated to this Fs implementation
  135. func (fs *S3Fs) ConnectionID() string {
  136. return fs.connectionID
  137. }
  138. // Stat returns a FileInfo describing the named file
  139. func (fs *S3Fs) Stat(name string) (os.FileInfo, error) {
  140. var result *FileInfo
  141. if name == "" || name == "/" || name == "." {
  142. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  143. }
  144. if fs.config.KeyPrefix == name+"/" {
  145. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  146. }
  147. obj, err := fs.headObject(name)
  148. if err == nil {
  149. // Some S3 providers (like SeaweedFS) remove the trailing '/' from object keys.
  150. // So we check some common content types to detect if this is a "directory".
  151. isDir := util.Contains(s3DirMimeTypes, util.GetStringFromPointer(obj.ContentType))
  152. if obj.ContentLength == 0 && !isDir {
  153. _, err = fs.headObject(name + "/")
  154. isDir = err == nil
  155. }
  156. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, isDir, obj.ContentLength,
  157. util.GetTimeFromPointer(obj.LastModified), false))
  158. }
  159. if !fs.IsNotExist(err) {
  160. return result, err
  161. }
  162. // now check if this is a prefix (virtual directory)
  163. hasContents, err := fs.hasContents(name)
  164. if err == nil && hasContents {
  165. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  166. } else if err != nil {
  167. return nil, err
  168. }
  169. // the requested file may still be a directory as a zero bytes key
  170. // with a trailing forward slash (created using mkdir).
  171. // S3 doesn't return content type when listing objects, so we have
  172. // create "dirs" adding a trailing "/" to the key
  173. return fs.getStatForDir(name)
  174. }
  175. func (fs *S3Fs) getStatForDir(name string) (os.FileInfo, error) {
  176. var result *FileInfo
  177. obj, err := fs.headObject(name + "/")
  178. if err != nil {
  179. return result, err
  180. }
  181. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, obj.ContentLength,
  182. util.GetTimeFromPointer(obj.LastModified), false))
  183. }
  184. // Lstat returns a FileInfo describing the named file
  185. func (fs *S3Fs) Lstat(name string) (os.FileInfo, error) {
  186. return fs.Stat(name)
  187. }
  188. // Open opens the named file for reading
  189. func (fs *S3Fs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  190. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  191. if err != nil {
  192. return nil, nil, nil, err
  193. }
  194. ctx, cancelFn := context.WithCancel(context.Background())
  195. downloader := manager.NewDownloader(fs.svc, func(d *manager.Downloader) {
  196. d.Concurrency = fs.config.DownloadConcurrency
  197. d.PartSize = fs.config.DownloadPartSize
  198. if offset == 0 && fs.config.DownloadPartMaxTime > 0 {
  199. d.ClientOptions = append(d.ClientOptions, func(o *s3.Options) {
  200. o.HTTPClient = getAWSHTTPClient(fs.config.DownloadPartMaxTime, 100*time.Millisecond)
  201. })
  202. }
  203. })
  204. var streamRange *string
  205. if offset > 0 {
  206. streamRange = aws.String(fmt.Sprintf("bytes=%v-", offset))
  207. }
  208. go func() {
  209. defer cancelFn()
  210. n, err := downloader.Download(ctx, w, &s3.GetObjectInput{
  211. Bucket: aws.String(fs.config.Bucket),
  212. Key: aws.String(name),
  213. Range: streamRange,
  214. })
  215. w.CloseWithError(err) //nolint:errcheck
  216. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %+v", name, n, err)
  217. metric.S3TransferCompleted(n, 1, err)
  218. }()
  219. return nil, r, cancelFn, nil
  220. }
  221. // Create creates or opens the named file for writing
  222. func (fs *S3Fs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  223. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  224. if err != nil {
  225. return nil, nil, nil, err
  226. }
  227. p := NewPipeWriter(w)
  228. ctx, cancelFn := context.WithCancel(context.Background())
  229. uploader := manager.NewUploader(fs.svc, func(u *manager.Uploader) {
  230. u.Concurrency = fs.config.UploadConcurrency
  231. u.PartSize = fs.config.UploadPartSize
  232. if fs.config.UploadPartMaxTime > 0 {
  233. u.ClientOptions = append(u.ClientOptions, func(o *s3.Options) {
  234. o.HTTPClient = getAWSHTTPClient(fs.config.UploadPartMaxTime, 100*time.Millisecond)
  235. })
  236. }
  237. })
  238. go func() {
  239. defer cancelFn()
  240. var contentType string
  241. if flag == -1 {
  242. contentType = s3DirMimeType
  243. } else {
  244. contentType = mime.TypeByExtension(path.Ext(name))
  245. }
  246. _, err := uploader.Upload(ctx, &s3.PutObjectInput{
  247. Bucket: aws.String(fs.config.Bucket),
  248. Key: aws.String(name),
  249. Body: r,
  250. ACL: types.ObjectCannedACL(fs.config.ACL),
  251. StorageClass: types.StorageClass(fs.config.StorageClass),
  252. ContentType: util.NilIfEmpty(contentType),
  253. })
  254. r.CloseWithError(err) //nolint:errcheck
  255. p.Done(err)
  256. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, acl: %#v, readed bytes: %v, err: %+v",
  257. name, fs.config.ACL, r.GetReadedBytes(), err)
  258. metric.S3TransferCompleted(r.GetReadedBytes(), 0, err)
  259. }()
  260. return nil, p, cancelFn, nil
  261. }
  262. // Rename renames (moves) source to target.
  263. // We don't support renaming non empty directories since we should
  264. // rename all the contents too and this could take long time: think
  265. // about directories with thousands of files, for each file we should
  266. // execute a CopyObject call.
  267. func (fs *S3Fs) Rename(source, target string) error {
  268. if source == target {
  269. return nil
  270. }
  271. fi, err := fs.Stat(source)
  272. if err != nil {
  273. return err
  274. }
  275. if fi.IsDir() {
  276. hasContents, err := fs.hasContents(source)
  277. if err != nil {
  278. return err
  279. }
  280. if hasContents {
  281. return fmt.Errorf("cannot rename non empty directory: %q", source)
  282. }
  283. if err := fs.mkdirInternal(target); err != nil {
  284. return err
  285. }
  286. } else {
  287. contentType := mime.TypeByExtension(path.Ext(source))
  288. copySource := pathEscape(fs.Join(fs.config.Bucket, source))
  289. if fi.Size() > 500*1024*1024 {
  290. fsLog(fs, logger.LevelDebug, "renaming file %q with size %d using multipart copy",
  291. source, fi.Size())
  292. err = fs.doMultipartCopy(copySource, target, contentType, fi.Size())
  293. } else {
  294. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  295. defer cancelFn()
  296. _, err = fs.svc.CopyObject(ctx, &s3.CopyObjectInput{
  297. Bucket: aws.String(fs.config.Bucket),
  298. CopySource: aws.String(copySource),
  299. Key: aws.String(target),
  300. StorageClass: types.StorageClass(fs.config.StorageClass),
  301. ACL: types.ObjectCannedACL(fs.config.ACL),
  302. ContentType: util.NilIfEmpty(contentType),
  303. })
  304. }
  305. if err != nil {
  306. metric.S3CopyObjectCompleted(err)
  307. return err
  308. }
  309. waiter := s3.NewObjectExistsWaiter(fs.svc)
  310. err = waiter.Wait(context.Background(), &s3.HeadObjectInput{
  311. Bucket: aws.String(fs.config.Bucket),
  312. Key: aws.String(target),
  313. }, 10*time.Second)
  314. metric.S3CopyObjectCompleted(err)
  315. if err != nil {
  316. return err
  317. }
  318. if plugin.Handler.HasMetadater() {
  319. err = plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(target),
  320. util.GetTimeAsMsSinceEpoch(fi.ModTime()))
  321. if err != nil {
  322. fsLog(fs, logger.LevelWarn, "unable to preserve modification time after renaming %#v -> %#v: %+v",
  323. source, target, err)
  324. }
  325. }
  326. }
  327. return fs.Remove(source, fi.IsDir())
  328. }
  329. // Remove removes the named file or (empty) directory.
  330. func (fs *S3Fs) Remove(name string, isDir bool) error {
  331. if isDir {
  332. hasContents, err := fs.hasContents(name)
  333. if err != nil {
  334. return err
  335. }
  336. if hasContents {
  337. return fmt.Errorf("cannot remove non empty directory: %#v", name)
  338. }
  339. if !strings.HasSuffix(name, "/") {
  340. name += "/"
  341. }
  342. }
  343. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  344. defer cancelFn()
  345. _, err := fs.svc.DeleteObject(ctx, &s3.DeleteObjectInput{
  346. Bucket: aws.String(fs.config.Bucket),
  347. Key: aws.String(name),
  348. })
  349. metric.S3DeleteObjectCompleted(err)
  350. if plugin.Handler.HasMetadater() && err == nil && !isDir {
  351. if errMetadata := plugin.Handler.RemoveMetadata(fs.getStorageID(), ensureAbsPath(name)); errMetadata != nil {
  352. fsLog(fs, logger.LevelWarn, "unable to remove metadata for path %#v: %+v", name, errMetadata)
  353. }
  354. }
  355. return err
  356. }
  357. // Mkdir creates a new directory with the specified name and default permissions
  358. func (fs *S3Fs) Mkdir(name string) error {
  359. _, err := fs.Stat(name)
  360. if !fs.IsNotExist(err) {
  361. return err
  362. }
  363. return fs.mkdirInternal(name)
  364. }
  365. // Symlink creates source as a symbolic link to target.
  366. func (*S3Fs) Symlink(source, target string) error {
  367. return ErrVfsUnsupported
  368. }
  369. // Readlink returns the destination of the named symbolic link
  370. func (*S3Fs) Readlink(name string) (string, error) {
  371. return "", ErrVfsUnsupported
  372. }
  373. // Chown changes the numeric uid and gid of the named file.
  374. func (*S3Fs) Chown(name string, uid int, gid int) error {
  375. return ErrVfsUnsupported
  376. }
  377. // Chmod changes the mode of the named file to mode.
  378. func (*S3Fs) Chmod(name string, mode os.FileMode) error {
  379. return ErrVfsUnsupported
  380. }
  381. // Chtimes changes the access and modification times of the named file.
  382. func (fs *S3Fs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  383. if !plugin.Handler.HasMetadater() {
  384. return ErrVfsUnsupported
  385. }
  386. if !isUploading {
  387. info, err := fs.Stat(name)
  388. if err != nil {
  389. return err
  390. }
  391. if info.IsDir() {
  392. return ErrVfsUnsupported
  393. }
  394. }
  395. return plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(name),
  396. util.GetTimeAsMsSinceEpoch(mtime))
  397. }
  398. // Truncate changes the size of the named file.
  399. // Truncate by path is not supported, while truncating an opened
  400. // file is handled inside base transfer
  401. func (*S3Fs) Truncate(name string, size int64) error {
  402. return ErrVfsUnsupported
  403. }
  404. // ReadDir reads the directory named by dirname and returns
  405. // a list of directory entries.
  406. func (fs *S3Fs) ReadDir(dirname string) ([]os.FileInfo, error) {
  407. var result []os.FileInfo
  408. // dirname must be already cleaned
  409. prefix := fs.getPrefix(dirname)
  410. modTimes, err := getFolderModTimes(fs.getStorageID(), dirname)
  411. if err != nil {
  412. return result, err
  413. }
  414. prefixes := make(map[string]bool)
  415. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  416. Bucket: aws.String(fs.config.Bucket),
  417. Prefix: aws.String(prefix),
  418. Delimiter: aws.String("/"),
  419. })
  420. for paginator.HasMorePages() {
  421. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  422. defer cancelFn()
  423. page, err := paginator.NextPage(ctx)
  424. if err != nil {
  425. metric.S3ListObjectsCompleted(err)
  426. return result, err
  427. }
  428. for _, p := range page.CommonPrefixes {
  429. // prefixes have a trailing slash
  430. name, _ := fs.resolve(p.Prefix, prefix)
  431. if name == "" {
  432. continue
  433. }
  434. if _, ok := prefixes[name]; ok {
  435. continue
  436. }
  437. result = append(result, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  438. prefixes[name] = true
  439. }
  440. for _, fileObject := range page.Contents {
  441. objectModTime := util.GetTimeFromPointer(fileObject.LastModified)
  442. name, isDir := fs.resolve(fileObject.Key, prefix)
  443. if name == "" || name == "/" {
  444. continue
  445. }
  446. if isDir {
  447. if _, ok := prefixes[name]; ok {
  448. continue
  449. }
  450. prefixes[name] = true
  451. }
  452. if t, ok := modTimes[name]; ok {
  453. objectModTime = util.GetTimeFromMsecSinceEpoch(t)
  454. }
  455. result = append(result, NewFileInfo(name, (isDir && fileObject.Size == 0), fileObject.Size,
  456. objectModTime, false))
  457. }
  458. }
  459. metric.S3ListObjectsCompleted(nil)
  460. return result, nil
  461. }
  462. // IsUploadResumeSupported returns true if resuming uploads is supported.
  463. // Resuming uploads is not supported on S3
  464. func (*S3Fs) IsUploadResumeSupported() bool {
  465. return false
  466. }
  467. // IsAtomicUploadSupported returns true if atomic upload is supported.
  468. // S3 uploads are already atomic, we don't need to upload to a temporary
  469. // file
  470. func (*S3Fs) IsAtomicUploadSupported() bool {
  471. return false
  472. }
  473. // IsNotExist returns a boolean indicating whether the error is known to
  474. // report that a file or directory does not exist
  475. func (*S3Fs) IsNotExist(err error) bool {
  476. if err == nil {
  477. return false
  478. }
  479. var re *awshttp.ResponseError
  480. if errors.As(err, &re) {
  481. if re.Response != nil {
  482. return re.Response.StatusCode == http.StatusNotFound
  483. }
  484. }
  485. return false
  486. }
  487. // IsPermission returns a boolean indicating whether the error is known to
  488. // report that permission is denied.
  489. func (*S3Fs) IsPermission(err error) bool {
  490. if err == nil {
  491. return false
  492. }
  493. var re *awshttp.ResponseError
  494. if errors.As(err, &re) {
  495. if re.Response != nil {
  496. return re.Response.StatusCode == http.StatusForbidden ||
  497. re.Response.StatusCode == http.StatusUnauthorized
  498. }
  499. }
  500. return false
  501. }
  502. // IsNotSupported returns true if the error indicate an unsupported operation
  503. func (*S3Fs) IsNotSupported(err error) bool {
  504. if err == nil {
  505. return false
  506. }
  507. return err == ErrVfsUnsupported
  508. }
  509. // CheckRootPath creates the specified local root directory if it does not exists
  510. func (fs *S3Fs) CheckRootPath(username string, uid int, gid int) bool {
  511. // we need a local directory for temporary files
  512. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  513. return osFs.CheckRootPath(username, uid, gid)
  514. }
  515. // ScanRootDirContents returns the number of files contained in the bucket,
  516. // and their size
  517. func (fs *S3Fs) ScanRootDirContents() (int, int64, error) {
  518. return fs.GetDirSize(fs.config.KeyPrefix)
  519. }
  520. func (fs *S3Fs) getFileNamesInPrefix(fsPrefix string) (map[string]bool, error) {
  521. fileNames := make(map[string]bool)
  522. prefix := ""
  523. if fsPrefix != "/" {
  524. prefix = strings.TrimPrefix(fsPrefix, "/")
  525. }
  526. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  527. Bucket: aws.String(fs.config.Bucket),
  528. Prefix: aws.String(prefix),
  529. Delimiter: aws.String("/"),
  530. })
  531. for paginator.HasMorePages() {
  532. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  533. defer cancelFn()
  534. page, err := paginator.NextPage(ctx)
  535. if err != nil {
  536. metric.S3ListObjectsCompleted(err)
  537. if err != nil {
  538. fsLog(fs, logger.LevelError, "unable to get content for prefix %#v: %+v", prefix, err)
  539. return nil, err
  540. }
  541. return fileNames, err
  542. }
  543. for _, fileObject := range page.Contents {
  544. name, isDir := fs.resolve(fileObject.Key, prefix)
  545. if name != "" && !isDir {
  546. fileNames[name] = true
  547. }
  548. }
  549. }
  550. metric.S3ListObjectsCompleted(nil)
  551. return fileNames, nil
  552. }
  553. // CheckMetadata checks the metadata consistency
  554. func (fs *S3Fs) CheckMetadata() error {
  555. return fsMetadataCheck(fs, fs.getStorageID(), fs.config.KeyPrefix)
  556. }
  557. // GetDirSize returns the number of files and the size for a folder
  558. // including any subfolders
  559. func (fs *S3Fs) GetDirSize(dirname string) (int, int64, error) {
  560. prefix := fs.getPrefix(dirname)
  561. numFiles := 0
  562. size := int64(0)
  563. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  564. Bucket: aws.String(fs.config.Bucket),
  565. Prefix: aws.String(prefix),
  566. })
  567. for paginator.HasMorePages() {
  568. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  569. defer cancelFn()
  570. page, err := paginator.NextPage(ctx)
  571. if err != nil {
  572. metric.S3ListObjectsCompleted(err)
  573. return numFiles, size, err
  574. }
  575. for _, fileObject := range page.Contents {
  576. isDir := strings.HasSuffix(util.GetStringFromPointer(fileObject.Key), "/")
  577. if isDir && fileObject.Size == 0 {
  578. continue
  579. }
  580. numFiles++
  581. size += fileObject.Size
  582. if numFiles%1000 == 0 {
  583. fsLog(fs, logger.LevelDebug, "dirname %q scan in progress, files: %d, size: %d", dirname, numFiles, size)
  584. }
  585. }
  586. }
  587. metric.S3ListObjectsCompleted(nil)
  588. return numFiles, size, nil
  589. }
  590. // GetAtomicUploadPath returns the path to use for an atomic upload.
  591. // S3 uploads are already atomic, we never call this method for S3
  592. func (*S3Fs) GetAtomicUploadPath(name string) string {
  593. return ""
  594. }
  595. // GetRelativePath returns the path for a file relative to the user's home dir.
  596. // This is the path as seen by SFTPGo users
  597. func (fs *S3Fs) GetRelativePath(name string) string {
  598. rel := path.Clean(name)
  599. if rel == "." {
  600. rel = ""
  601. }
  602. if !path.IsAbs(rel) {
  603. rel = "/" + rel
  604. }
  605. if fs.config.KeyPrefix != "" {
  606. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  607. rel = "/"
  608. }
  609. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  610. }
  611. if fs.mountPath != "" {
  612. rel = path.Join(fs.mountPath, rel)
  613. }
  614. return rel
  615. }
  616. // Walk walks the file tree rooted at root, calling walkFn for each file or
  617. // directory in the tree, including root. The result are unordered
  618. func (fs *S3Fs) Walk(root string, walkFn filepath.WalkFunc) error {
  619. prefix := fs.getPrefix(root)
  620. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  621. Bucket: aws.String(fs.config.Bucket),
  622. Prefix: aws.String(prefix),
  623. })
  624. for paginator.HasMorePages() {
  625. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  626. defer cancelFn()
  627. page, err := paginator.NextPage(ctx)
  628. if err != nil {
  629. metric.S3ListObjectsCompleted(err)
  630. walkFn(root, NewFileInfo(root, true, 0, time.Unix(0, 0), false), err) //nolint:errcheck
  631. return err
  632. }
  633. for _, fileObject := range page.Contents {
  634. name, isDir := fs.resolve(fileObject.Key, prefix)
  635. if name == "" {
  636. continue
  637. }
  638. err := walkFn(util.GetStringFromPointer(fileObject.Key),
  639. NewFileInfo(name, isDir, fileObject.Size, util.GetTimeFromPointer(fileObject.LastModified), false), nil)
  640. if err != nil {
  641. return err
  642. }
  643. }
  644. }
  645. metric.S3ListObjectsCompleted(nil)
  646. walkFn(root, NewFileInfo(root, true, 0, time.Unix(0, 0), false), nil) //nolint:errcheck
  647. return nil
  648. }
  649. // Join joins any number of path elements into a single path
  650. func (*S3Fs) Join(elem ...string) string {
  651. return strings.TrimPrefix(path.Join(elem...), "/")
  652. }
  653. // HasVirtualFolders returns true if folders are emulated
  654. func (*S3Fs) HasVirtualFolders() bool {
  655. return true
  656. }
  657. // ResolvePath returns the matching filesystem path for the specified virtual path
  658. func (fs *S3Fs) ResolvePath(virtualPath string) (string, error) {
  659. if fs.mountPath != "" {
  660. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  661. }
  662. if !path.IsAbs(virtualPath) {
  663. virtualPath = path.Clean("/" + virtualPath)
  664. }
  665. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  666. }
  667. func (fs *S3Fs) resolve(name *string, prefix string) (string, bool) {
  668. result := strings.TrimPrefix(util.GetStringFromPointer(name), prefix)
  669. isDir := strings.HasSuffix(result, "/")
  670. if isDir {
  671. result = strings.TrimSuffix(result, "/")
  672. }
  673. return result, isDir
  674. }
  675. func (fs *S3Fs) setConfigDefaults() {
  676. if fs.config.UploadPartSize == 0 {
  677. fs.config.UploadPartSize = manager.DefaultUploadPartSize
  678. } else {
  679. if fs.config.UploadPartSize < 1024*1024 {
  680. fs.config.UploadPartSize *= 1024 * 1024
  681. }
  682. }
  683. if fs.config.UploadConcurrency == 0 {
  684. fs.config.UploadConcurrency = manager.DefaultUploadConcurrency
  685. }
  686. if fs.config.DownloadPartSize == 0 {
  687. fs.config.DownloadPartSize = manager.DefaultDownloadPartSize
  688. } else {
  689. if fs.config.DownloadPartSize < 1024*1024 {
  690. fs.config.DownloadPartSize *= 1024 * 1024
  691. }
  692. }
  693. if fs.config.DownloadConcurrency == 0 {
  694. fs.config.DownloadConcurrency = manager.DefaultDownloadConcurrency
  695. }
  696. }
  697. func (fs *S3Fs) mkdirInternal(name string) error {
  698. if !strings.HasSuffix(name, "/") {
  699. name += "/"
  700. }
  701. _, w, _, err := fs.Create(name, -1)
  702. if err != nil {
  703. return err
  704. }
  705. return w.Close()
  706. }
  707. func (fs *S3Fs) hasContents(name string) (bool, error) {
  708. prefix := fs.getPrefix(name)
  709. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  710. Bucket: aws.String(fs.config.Bucket),
  711. Prefix: aws.String(prefix),
  712. MaxKeys: 2,
  713. })
  714. if paginator.HasMorePages() {
  715. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  716. defer cancelFn()
  717. page, err := paginator.NextPage(ctx)
  718. metric.S3ListObjectsCompleted(err)
  719. if err != nil {
  720. return false, err
  721. }
  722. for _, obj := range page.Contents {
  723. name, _ := fs.resolve(obj.Key, prefix)
  724. if name == "" || name == "/" {
  725. continue
  726. }
  727. return true, nil
  728. }
  729. return false, nil
  730. }
  731. metric.S3ListObjectsCompleted(nil)
  732. return false, nil
  733. }
  734. func (fs *S3Fs) doMultipartCopy(source, target, contentType string, fileSize int64) error {
  735. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  736. defer cancelFn()
  737. res, err := fs.svc.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{
  738. Bucket: aws.String(fs.config.Bucket),
  739. Key: aws.String(target),
  740. StorageClass: types.StorageClass(fs.config.StorageClass),
  741. ACL: types.ObjectCannedACL(fs.config.ACL),
  742. ContentType: util.NilIfEmpty(contentType),
  743. })
  744. if err != nil {
  745. return fmt.Errorf("unable to create multipart copy request: %w", err)
  746. }
  747. uploadID := util.GetStringFromPointer(res.UploadId)
  748. if uploadID == "" {
  749. return errors.New("unable to get multipart copy upload ID")
  750. }
  751. // We use 32 MB part size and copy 10 parts in parallel.
  752. // These values are arbitrary. We don't want to start too many goroutines
  753. maxPartSize := int64(32 * 1024 * 1024)
  754. if fileSize > int64(100*1024*1024*1024) {
  755. maxPartSize = int64(500 * 1024 * 1024)
  756. }
  757. guard := make(chan struct{}, 10)
  758. finished := false
  759. var completedParts []types.CompletedPart
  760. var partMutex sync.Mutex
  761. var wg sync.WaitGroup
  762. var hasError atomic.Bool
  763. var errOnce sync.Once
  764. var copyError error
  765. var partNumber int32
  766. var offset int64
  767. opCtx, opCancel := context.WithCancel(context.Background())
  768. defer opCancel()
  769. for partNumber = 1; !finished; partNumber++ {
  770. start := offset
  771. end := offset + maxPartSize
  772. if end >= fileSize {
  773. end = fileSize
  774. finished = true
  775. }
  776. offset = end
  777. guard <- struct{}{}
  778. if hasError.Load() {
  779. fsLog(fs, logger.LevelDebug, "previous multipart copy error, copy for part %d not started", partNumber)
  780. break
  781. }
  782. wg.Add(1)
  783. go func(partNum int32, partStart, partEnd int64) {
  784. defer func() {
  785. <-guard
  786. wg.Done()
  787. }()
  788. innerCtx, innerCancelFn := context.WithDeadline(opCtx, time.Now().Add(fs.ctxTimeout))
  789. defer innerCancelFn()
  790. partResp, err := fs.svc.UploadPartCopy(innerCtx, &s3.UploadPartCopyInput{
  791. Bucket: aws.String(fs.config.Bucket),
  792. CopySource: aws.String(source),
  793. Key: aws.String(target),
  794. PartNumber: partNum,
  795. UploadId: aws.String(uploadID),
  796. CopySourceRange: aws.String(fmt.Sprintf("bytes=%d-%d", partStart, partEnd-1)),
  797. })
  798. if err != nil {
  799. errOnce.Do(func() {
  800. fsLog(fs, logger.LevelError, "unable to copy part number %d: %+v", partNum, err)
  801. hasError.Store(true)
  802. copyError = fmt.Errorf("error copying part number %d: %w", partNum, err)
  803. opCancel()
  804. abortCtx, abortCancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  805. defer abortCancelFn()
  806. _, errAbort := fs.svc.AbortMultipartUpload(abortCtx, &s3.AbortMultipartUploadInput{
  807. Bucket: aws.String(fs.config.Bucket),
  808. Key: aws.String(target),
  809. UploadId: aws.String(uploadID),
  810. })
  811. if errAbort != nil {
  812. fsLog(fs, logger.LevelError, "unable to abort multipart copy: %+v", errAbort)
  813. }
  814. })
  815. return
  816. }
  817. partMutex.Lock()
  818. completedParts = append(completedParts, types.CompletedPart{
  819. ETag: partResp.CopyPartResult.ETag,
  820. PartNumber: partNum,
  821. })
  822. partMutex.Unlock()
  823. }(partNumber, start, end)
  824. }
  825. wg.Wait()
  826. close(guard)
  827. if copyError != nil {
  828. return copyError
  829. }
  830. sort.Slice(completedParts, func(i, j int) bool {
  831. return completedParts[i].PartNumber < completedParts[j].PartNumber
  832. })
  833. completeCtx, completeCancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  834. defer completeCancelFn()
  835. _, err = fs.svc.CompleteMultipartUpload(completeCtx, &s3.CompleteMultipartUploadInput{
  836. Bucket: aws.String(fs.config.Bucket),
  837. Key: aws.String(target),
  838. UploadId: aws.String(uploadID),
  839. MultipartUpload: &types.CompletedMultipartUpload{
  840. Parts: completedParts,
  841. },
  842. })
  843. if err != nil {
  844. return fmt.Errorf("unable to complete multipart upload: %w", err)
  845. }
  846. return nil
  847. }
  848. func (fs *S3Fs) getPrefix(name string) string {
  849. prefix := ""
  850. if name != "" && name != "." && name != "/" {
  851. prefix = strings.TrimPrefix(name, "/")
  852. if !strings.HasSuffix(prefix, "/") {
  853. prefix += "/"
  854. }
  855. }
  856. return prefix
  857. }
  858. func (fs *S3Fs) headObject(name string) (*s3.HeadObjectOutput, error) {
  859. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  860. defer cancelFn()
  861. obj, err := fs.svc.HeadObject(ctx, &s3.HeadObjectInput{
  862. Bucket: aws.String(fs.config.Bucket),
  863. Key: aws.String(name),
  864. })
  865. metric.S3HeadObjectCompleted(err)
  866. return obj, err
  867. }
  868. // GetMimeType returns the content type
  869. func (fs *S3Fs) GetMimeType(name string) (string, error) {
  870. obj, err := fs.headObject(name)
  871. if err != nil {
  872. return "", err
  873. }
  874. return util.GetStringFromPointer(obj.ContentType), nil
  875. }
  876. // Close closes the fs
  877. func (*S3Fs) Close() error {
  878. return nil
  879. }
  880. // GetAvailableDiskSize returns the available size for the specified path
  881. func (*S3Fs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  882. return nil, ErrStorageSizeUnavailable
  883. }
  884. func (fs *S3Fs) getStorageID() string {
  885. if fs.config.Endpoint != "" {
  886. if !strings.HasSuffix(fs.config.Endpoint, "/") {
  887. return fmt.Sprintf("s3://%v/%v", fs.config.Endpoint, fs.config.Bucket)
  888. }
  889. return fmt.Sprintf("s3://%v%v", fs.config.Endpoint, fs.config.Bucket)
  890. }
  891. return fmt.Sprintf("s3://%v", fs.config.Bucket)
  892. }
  893. func getAWSHTTPClient(timeout int, idleConnectionTimeout time.Duration) *awshttp.BuildableClient {
  894. c := awshttp.NewBuildableClient().
  895. WithDialerOptions(func(d *net.Dialer) {
  896. d.Timeout = 8 * time.Second
  897. }).
  898. WithTransportOptions(func(tr *http.Transport) {
  899. tr.IdleConnTimeout = idleConnectionTimeout
  900. tr.WriteBufferSize = s3TransferBufferSize
  901. tr.ReadBufferSize = s3TransferBufferSize
  902. })
  903. if timeout > 0 {
  904. c = c.WithTimeout(time.Duration(timeout) * time.Second)
  905. }
  906. return c
  907. }
  908. // ideally we should simply use url.PathEscape:
  909. //
  910. // https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/go/example_code/s3/s3_copy_object.go#L65
  911. //
  912. // but this cause issue with some vendors, see #483, the code below is copied from rclone
  913. func pathEscape(in string) string {
  914. var u url.URL
  915. u.Path = in
  916. return strings.ReplaceAll(u.String(), "+", "%2B")
  917. }