s3fs.go 28 KB

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