s3fs.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. //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. func (fs *S3Fs) Rename(source, target string) (int, int64, error) {
  264. if source == target {
  265. return -1, -1, nil
  266. }
  267. fi, err := fs.Stat(source)
  268. if err != nil {
  269. return -1, -1, err
  270. }
  271. return fs.renameInternal(source, target, fi)
  272. }
  273. // Remove removes the named file or (empty) directory.
  274. func (fs *S3Fs) Remove(name string, isDir bool) error {
  275. if isDir {
  276. hasContents, err := fs.hasContents(name)
  277. if err != nil {
  278. return err
  279. }
  280. if hasContents {
  281. return fmt.Errorf("cannot remove non empty directory: %#v", name)
  282. }
  283. if !strings.HasSuffix(name, "/") {
  284. name += "/"
  285. }
  286. }
  287. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  288. defer cancelFn()
  289. _, err := fs.svc.DeleteObject(ctx, &s3.DeleteObjectInput{
  290. Bucket: aws.String(fs.config.Bucket),
  291. Key: aws.String(name),
  292. })
  293. metric.S3DeleteObjectCompleted(err)
  294. if plugin.Handler.HasMetadater() && err == nil && !isDir {
  295. if errMetadata := plugin.Handler.RemoveMetadata(fs.getStorageID(), ensureAbsPath(name)); errMetadata != nil {
  296. fsLog(fs, logger.LevelWarn, "unable to remove metadata for path %#v: %+v", name, errMetadata)
  297. }
  298. }
  299. return err
  300. }
  301. // Mkdir creates a new directory with the specified name and default permissions
  302. func (fs *S3Fs) Mkdir(name string) error {
  303. _, err := fs.Stat(name)
  304. if !fs.IsNotExist(err) {
  305. return err
  306. }
  307. return fs.mkdirInternal(name)
  308. }
  309. // Symlink creates source as a symbolic link to target.
  310. func (*S3Fs) Symlink(source, target string) error {
  311. return ErrVfsUnsupported
  312. }
  313. // Readlink returns the destination of the named symbolic link
  314. func (*S3Fs) Readlink(name string) (string, error) {
  315. return "", ErrVfsUnsupported
  316. }
  317. // Chown changes the numeric uid and gid of the named file.
  318. func (*S3Fs) Chown(name string, uid int, gid int) error {
  319. return ErrVfsUnsupported
  320. }
  321. // Chmod changes the mode of the named file to mode.
  322. func (*S3Fs) Chmod(name string, mode os.FileMode) error {
  323. return ErrVfsUnsupported
  324. }
  325. // Chtimes changes the access and modification times of the named file.
  326. func (fs *S3Fs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  327. if !plugin.Handler.HasMetadater() {
  328. return ErrVfsUnsupported
  329. }
  330. if !isUploading {
  331. info, err := fs.Stat(name)
  332. if err != nil {
  333. return err
  334. }
  335. if info.IsDir() {
  336. return ErrVfsUnsupported
  337. }
  338. }
  339. return plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(name),
  340. util.GetTimeAsMsSinceEpoch(mtime))
  341. }
  342. // Truncate changes the size of the named file.
  343. // Truncate by path is not supported, while truncating an opened
  344. // file is handled inside base transfer
  345. func (*S3Fs) Truncate(name string, size int64) error {
  346. return ErrVfsUnsupported
  347. }
  348. // ReadDir reads the directory named by dirname and returns
  349. // a list of directory entries.
  350. func (fs *S3Fs) ReadDir(dirname string) ([]os.FileInfo, error) {
  351. var result []os.FileInfo
  352. // dirname must be already cleaned
  353. prefix := fs.getPrefix(dirname)
  354. modTimes, err := getFolderModTimes(fs.getStorageID(), dirname)
  355. if err != nil {
  356. return result, err
  357. }
  358. prefixes := make(map[string]bool)
  359. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  360. Bucket: aws.String(fs.config.Bucket),
  361. Prefix: aws.String(prefix),
  362. Delimiter: aws.String("/"),
  363. })
  364. for paginator.HasMorePages() {
  365. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  366. defer cancelFn()
  367. page, err := paginator.NextPage(ctx)
  368. if err != nil {
  369. metric.S3ListObjectsCompleted(err)
  370. return result, err
  371. }
  372. for _, p := range page.CommonPrefixes {
  373. // prefixes have a trailing slash
  374. name, _ := fs.resolve(p.Prefix, prefix)
  375. if name == "" {
  376. continue
  377. }
  378. if _, ok := prefixes[name]; ok {
  379. continue
  380. }
  381. result = append(result, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  382. prefixes[name] = true
  383. }
  384. for _, fileObject := range page.Contents {
  385. objectModTime := util.GetTimeFromPointer(fileObject.LastModified)
  386. name, isDir := fs.resolve(fileObject.Key, prefix)
  387. if name == "" || name == "/" {
  388. continue
  389. }
  390. if isDir {
  391. if _, ok := prefixes[name]; ok {
  392. continue
  393. }
  394. prefixes[name] = true
  395. }
  396. if t, ok := modTimes[name]; ok {
  397. objectModTime = util.GetTimeFromMsecSinceEpoch(t)
  398. }
  399. result = append(result, NewFileInfo(name, (isDir && fileObject.Size == 0), fileObject.Size,
  400. objectModTime, false))
  401. }
  402. }
  403. metric.S3ListObjectsCompleted(nil)
  404. return result, nil
  405. }
  406. // IsUploadResumeSupported returns true if resuming uploads is supported.
  407. // Resuming uploads is not supported on S3
  408. func (*S3Fs) IsUploadResumeSupported() bool {
  409. return false
  410. }
  411. // IsAtomicUploadSupported returns true if atomic upload is supported.
  412. // S3 uploads are already atomic, we don't need to upload to a temporary
  413. // file
  414. func (*S3Fs) IsAtomicUploadSupported() bool {
  415. return false
  416. }
  417. // IsNotExist returns a boolean indicating whether the error is known to
  418. // report that a file or directory does not exist
  419. func (*S3Fs) IsNotExist(err error) bool {
  420. if err == nil {
  421. return false
  422. }
  423. var re *awshttp.ResponseError
  424. if errors.As(err, &re) {
  425. if re.Response != nil {
  426. return re.Response.StatusCode == http.StatusNotFound
  427. }
  428. }
  429. return false
  430. }
  431. // IsPermission returns a boolean indicating whether the error is known to
  432. // report that permission is denied.
  433. func (*S3Fs) IsPermission(err error) bool {
  434. if err == nil {
  435. return false
  436. }
  437. var re *awshttp.ResponseError
  438. if errors.As(err, &re) {
  439. if re.Response != nil {
  440. return re.Response.StatusCode == http.StatusForbidden ||
  441. re.Response.StatusCode == http.StatusUnauthorized
  442. }
  443. }
  444. return false
  445. }
  446. // IsNotSupported returns true if the error indicate an unsupported operation
  447. func (*S3Fs) IsNotSupported(err error) bool {
  448. if err == nil {
  449. return false
  450. }
  451. return err == ErrVfsUnsupported
  452. }
  453. // CheckRootPath creates the specified local root directory if it does not exists
  454. func (fs *S3Fs) CheckRootPath(username string, uid int, gid int) bool {
  455. // we need a local directory for temporary files
  456. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  457. return osFs.CheckRootPath(username, uid, gid)
  458. }
  459. // ScanRootDirContents returns the number of files contained in the bucket,
  460. // and their size
  461. func (fs *S3Fs) ScanRootDirContents() (int, int64, error) {
  462. return fs.GetDirSize(fs.config.KeyPrefix)
  463. }
  464. func (fs *S3Fs) getFileNamesInPrefix(fsPrefix string) (map[string]bool, error) {
  465. fileNames := make(map[string]bool)
  466. prefix := ""
  467. if fsPrefix != "/" {
  468. prefix = strings.TrimPrefix(fsPrefix, "/")
  469. }
  470. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  471. Bucket: aws.String(fs.config.Bucket),
  472. Prefix: aws.String(prefix),
  473. Delimiter: aws.String("/"),
  474. })
  475. for paginator.HasMorePages() {
  476. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  477. defer cancelFn()
  478. page, err := paginator.NextPage(ctx)
  479. if err != nil {
  480. metric.S3ListObjectsCompleted(err)
  481. if err != nil {
  482. fsLog(fs, logger.LevelError, "unable to get content for prefix %#v: %+v", prefix, err)
  483. return nil, err
  484. }
  485. return fileNames, err
  486. }
  487. for _, fileObject := range page.Contents {
  488. name, isDir := fs.resolve(fileObject.Key, prefix)
  489. if name != "" && !isDir {
  490. fileNames[name] = true
  491. }
  492. }
  493. }
  494. metric.S3ListObjectsCompleted(nil)
  495. return fileNames, nil
  496. }
  497. // CheckMetadata checks the metadata consistency
  498. func (fs *S3Fs) CheckMetadata() error {
  499. return fsMetadataCheck(fs, fs.getStorageID(), fs.config.KeyPrefix)
  500. }
  501. // GetDirSize returns the number of files and the size for a folder
  502. // including any subfolders
  503. func (fs *S3Fs) GetDirSize(dirname string) (int, int64, error) {
  504. prefix := fs.getPrefix(dirname)
  505. numFiles := 0
  506. size := int64(0)
  507. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  508. Bucket: aws.String(fs.config.Bucket),
  509. Prefix: aws.String(prefix),
  510. })
  511. for paginator.HasMorePages() {
  512. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  513. defer cancelFn()
  514. page, err := paginator.NextPage(ctx)
  515. if err != nil {
  516. metric.S3ListObjectsCompleted(err)
  517. return numFiles, size, err
  518. }
  519. for _, fileObject := range page.Contents {
  520. isDir := strings.HasSuffix(util.GetStringFromPointer(fileObject.Key), "/")
  521. if isDir && fileObject.Size == 0 {
  522. continue
  523. }
  524. numFiles++
  525. size += fileObject.Size
  526. if numFiles%1000 == 0 {
  527. fsLog(fs, logger.LevelDebug, "dirname %q scan in progress, files: %d, size: %d", dirname, numFiles, size)
  528. }
  529. }
  530. }
  531. metric.S3ListObjectsCompleted(nil)
  532. return numFiles, size, nil
  533. }
  534. // GetAtomicUploadPath returns the path to use for an atomic upload.
  535. // S3 uploads are already atomic, we never call this method for S3
  536. func (*S3Fs) GetAtomicUploadPath(name string) string {
  537. return ""
  538. }
  539. // GetRelativePath returns the path for a file relative to the user's home dir.
  540. // This is the path as seen by SFTPGo users
  541. func (fs *S3Fs) GetRelativePath(name string) string {
  542. rel := path.Clean(name)
  543. if rel == "." {
  544. rel = ""
  545. }
  546. if !path.IsAbs(rel) {
  547. rel = "/" + rel
  548. }
  549. if fs.config.KeyPrefix != "" {
  550. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  551. rel = "/"
  552. }
  553. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  554. }
  555. if fs.mountPath != "" {
  556. rel = path.Join(fs.mountPath, rel)
  557. }
  558. return rel
  559. }
  560. // Walk walks the file tree rooted at root, calling walkFn for each file or
  561. // directory in the tree, including root. The result are unordered
  562. func (fs *S3Fs) Walk(root string, walkFn filepath.WalkFunc) error {
  563. prefix := fs.getPrefix(root)
  564. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  565. Bucket: aws.String(fs.config.Bucket),
  566. Prefix: aws.String(prefix),
  567. })
  568. for paginator.HasMorePages() {
  569. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  570. defer cancelFn()
  571. page, err := paginator.NextPage(ctx)
  572. if err != nil {
  573. metric.S3ListObjectsCompleted(err)
  574. walkFn(root, NewFileInfo(root, true, 0, time.Unix(0, 0), false), err) //nolint:errcheck
  575. return err
  576. }
  577. for _, fileObject := range page.Contents {
  578. name, isDir := fs.resolve(fileObject.Key, prefix)
  579. if name == "" {
  580. continue
  581. }
  582. err := walkFn(util.GetStringFromPointer(fileObject.Key),
  583. NewFileInfo(name, isDir, fileObject.Size, util.GetTimeFromPointer(fileObject.LastModified), false), nil)
  584. if err != nil {
  585. return err
  586. }
  587. }
  588. }
  589. metric.S3ListObjectsCompleted(nil)
  590. walkFn(root, NewFileInfo(root, true, 0, time.Unix(0, 0), false), nil) //nolint:errcheck
  591. return nil
  592. }
  593. // Join joins any number of path elements into a single path
  594. func (*S3Fs) Join(elem ...string) string {
  595. return strings.TrimPrefix(path.Join(elem...), "/")
  596. }
  597. // HasVirtualFolders returns true if folders are emulated
  598. func (*S3Fs) HasVirtualFolders() bool {
  599. return true
  600. }
  601. // ResolvePath returns the matching filesystem path for the specified virtual path
  602. func (fs *S3Fs) ResolvePath(virtualPath string) (string, error) {
  603. if fs.mountPath != "" {
  604. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  605. }
  606. if !path.IsAbs(virtualPath) {
  607. virtualPath = path.Clean("/" + virtualPath)
  608. }
  609. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  610. }
  611. // CopyFile implements the FsFileCopier interface
  612. func (fs *S3Fs) CopyFile(source, target string, srcSize int64) error {
  613. return fs.copyFileInternal(source, target, srcSize)
  614. }
  615. func (fs *S3Fs) resolve(name *string, prefix string) (string, bool) {
  616. result := strings.TrimPrefix(util.GetStringFromPointer(name), prefix)
  617. isDir := strings.HasSuffix(result, "/")
  618. if isDir {
  619. result = strings.TrimSuffix(result, "/")
  620. }
  621. return result, isDir
  622. }
  623. func (fs *S3Fs) setConfigDefaults() {
  624. if fs.config.UploadPartSize == 0 {
  625. fs.config.UploadPartSize = manager.DefaultUploadPartSize
  626. } else {
  627. if fs.config.UploadPartSize < 1024*1024 {
  628. fs.config.UploadPartSize *= 1024 * 1024
  629. }
  630. }
  631. if fs.config.UploadConcurrency == 0 {
  632. fs.config.UploadConcurrency = manager.DefaultUploadConcurrency
  633. }
  634. if fs.config.DownloadPartSize == 0 {
  635. fs.config.DownloadPartSize = manager.DefaultDownloadPartSize
  636. } else {
  637. if fs.config.DownloadPartSize < 1024*1024 {
  638. fs.config.DownloadPartSize *= 1024 * 1024
  639. }
  640. }
  641. if fs.config.DownloadConcurrency == 0 {
  642. fs.config.DownloadConcurrency = manager.DefaultDownloadConcurrency
  643. }
  644. }
  645. func (fs *S3Fs) copyFileInternal(source, target string, fileSize int64) error {
  646. contentType := mime.TypeByExtension(path.Ext(source))
  647. copySource := pathEscape(fs.Join(fs.config.Bucket, source))
  648. if fileSize > 500*1024*1024 {
  649. fsLog(fs, logger.LevelDebug, "renaming file %q with size %d using multipart copy",
  650. source, fileSize)
  651. err := fs.doMultipartCopy(copySource, target, contentType, fileSize)
  652. metric.S3CopyObjectCompleted(err)
  653. return err
  654. }
  655. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  656. defer cancelFn()
  657. _, err := fs.svc.CopyObject(ctx, &s3.CopyObjectInput{
  658. Bucket: aws.String(fs.config.Bucket),
  659. CopySource: aws.String(copySource),
  660. Key: aws.String(target),
  661. StorageClass: types.StorageClass(fs.config.StorageClass),
  662. ACL: types.ObjectCannedACL(fs.config.ACL),
  663. ContentType: util.NilIfEmpty(contentType),
  664. })
  665. metric.S3CopyObjectCompleted(err)
  666. return err
  667. }
  668. func (fs *S3Fs) renameInternal(source, target string, fi os.FileInfo) (int, int64, error) {
  669. var numFiles int
  670. var filesSize int64
  671. if fi.IsDir() {
  672. if renameMode == 0 {
  673. hasContents, err := fs.hasContents(source)
  674. if err != nil {
  675. return numFiles, filesSize, err
  676. }
  677. if hasContents {
  678. return numFiles, filesSize, fmt.Errorf("cannot rename non empty directory: %q", source)
  679. }
  680. }
  681. if err := fs.mkdirInternal(target); err != nil {
  682. return numFiles, filesSize, err
  683. }
  684. if renameMode == 1 {
  685. entries, err := fs.ReadDir(source)
  686. if err != nil {
  687. return numFiles, filesSize, err
  688. }
  689. for _, info := range entries {
  690. sourceEntry := fs.Join(source, info.Name())
  691. targetEntry := fs.Join(target, info.Name())
  692. files, size, err := fs.renameInternal(sourceEntry, targetEntry, info)
  693. if err != nil {
  694. return numFiles, filesSize, err
  695. }
  696. numFiles += files
  697. filesSize += size
  698. }
  699. }
  700. } else {
  701. if err := fs.copyFileInternal(source, target, fi.Size()); err != nil {
  702. return numFiles, filesSize, err
  703. }
  704. numFiles++
  705. filesSize += fi.Size()
  706. if plugin.Handler.HasMetadater() {
  707. err := plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(target),
  708. util.GetTimeAsMsSinceEpoch(fi.ModTime()))
  709. if err != nil {
  710. fsLog(fs, logger.LevelWarn, "unable to preserve modification time after renaming %q -> %q: %+v",
  711. source, target, err)
  712. }
  713. }
  714. }
  715. err := fs.Remove(source, fi.IsDir())
  716. if fs.IsNotExist(err) {
  717. err = nil
  718. }
  719. return numFiles, filesSize, err
  720. }
  721. func (fs *S3Fs) mkdirInternal(name string) error {
  722. if !strings.HasSuffix(name, "/") {
  723. name += "/"
  724. }
  725. _, w, _, err := fs.Create(name, -1)
  726. if err != nil {
  727. return err
  728. }
  729. return w.Close()
  730. }
  731. func (fs *S3Fs) hasContents(name string) (bool, error) {
  732. prefix := fs.getPrefix(name)
  733. paginator := s3.NewListObjectsV2Paginator(fs.svc, &s3.ListObjectsV2Input{
  734. Bucket: aws.String(fs.config.Bucket),
  735. Prefix: aws.String(prefix),
  736. MaxKeys: 2,
  737. })
  738. if paginator.HasMorePages() {
  739. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  740. defer cancelFn()
  741. page, err := paginator.NextPage(ctx)
  742. metric.S3ListObjectsCompleted(err)
  743. if err != nil {
  744. return false, err
  745. }
  746. for _, obj := range page.Contents {
  747. name, _ := fs.resolve(obj.Key, prefix)
  748. if name == "" || name == "/" {
  749. continue
  750. }
  751. return true, nil
  752. }
  753. return false, nil
  754. }
  755. metric.S3ListObjectsCompleted(nil)
  756. return false, nil
  757. }
  758. func (fs *S3Fs) doMultipartCopy(source, target, contentType string, fileSize int64) error {
  759. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  760. defer cancelFn()
  761. res, err := fs.svc.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{
  762. Bucket: aws.String(fs.config.Bucket),
  763. Key: aws.String(target),
  764. StorageClass: types.StorageClass(fs.config.StorageClass),
  765. ACL: types.ObjectCannedACL(fs.config.ACL),
  766. ContentType: util.NilIfEmpty(contentType),
  767. })
  768. if err != nil {
  769. return fmt.Errorf("unable to create multipart copy request: %w", err)
  770. }
  771. uploadID := util.GetStringFromPointer(res.UploadId)
  772. if uploadID == "" {
  773. return errors.New("unable to get multipart copy upload ID")
  774. }
  775. // We use 32 MB part size and copy 10 parts in parallel.
  776. // These values are arbitrary. We don't want to start too many goroutines
  777. maxPartSize := int64(32 * 1024 * 1024)
  778. if fileSize > int64(100*1024*1024*1024) {
  779. maxPartSize = int64(500 * 1024 * 1024)
  780. }
  781. guard := make(chan struct{}, 10)
  782. finished := false
  783. var completedParts []types.CompletedPart
  784. var partMutex sync.Mutex
  785. var wg sync.WaitGroup
  786. var hasError atomic.Bool
  787. var errOnce sync.Once
  788. var copyError error
  789. var partNumber int32
  790. var offset int64
  791. opCtx, opCancel := context.WithCancel(context.Background())
  792. defer opCancel()
  793. for partNumber = 1; !finished; partNumber++ {
  794. start := offset
  795. end := offset + maxPartSize
  796. if end >= fileSize {
  797. end = fileSize
  798. finished = true
  799. }
  800. offset = end
  801. guard <- struct{}{}
  802. if hasError.Load() {
  803. fsLog(fs, logger.LevelDebug, "previous multipart copy error, copy for part %d not started", partNumber)
  804. break
  805. }
  806. wg.Add(1)
  807. go func(partNum int32, partStart, partEnd int64) {
  808. defer func() {
  809. <-guard
  810. wg.Done()
  811. }()
  812. innerCtx, innerCancelFn := context.WithDeadline(opCtx, time.Now().Add(fs.ctxTimeout))
  813. defer innerCancelFn()
  814. partResp, err := fs.svc.UploadPartCopy(innerCtx, &s3.UploadPartCopyInput{
  815. Bucket: aws.String(fs.config.Bucket),
  816. CopySource: aws.String(source),
  817. Key: aws.String(target),
  818. PartNumber: partNum,
  819. UploadId: aws.String(uploadID),
  820. CopySourceRange: aws.String(fmt.Sprintf("bytes=%d-%d", partStart, partEnd-1)),
  821. })
  822. if err != nil {
  823. errOnce.Do(func() {
  824. fsLog(fs, logger.LevelError, "unable to copy part number %d: %+v", partNum, err)
  825. hasError.Store(true)
  826. copyError = fmt.Errorf("error copying part number %d: %w", partNum, err)
  827. opCancel()
  828. abortCtx, abortCancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  829. defer abortCancelFn()
  830. _, errAbort := fs.svc.AbortMultipartUpload(abortCtx, &s3.AbortMultipartUploadInput{
  831. Bucket: aws.String(fs.config.Bucket),
  832. Key: aws.String(target),
  833. UploadId: aws.String(uploadID),
  834. })
  835. if errAbort != nil {
  836. fsLog(fs, logger.LevelError, "unable to abort multipart copy: %+v", errAbort)
  837. }
  838. })
  839. return
  840. }
  841. partMutex.Lock()
  842. completedParts = append(completedParts, types.CompletedPart{
  843. ETag: partResp.CopyPartResult.ETag,
  844. PartNumber: partNum,
  845. })
  846. partMutex.Unlock()
  847. }(partNumber, start, end)
  848. }
  849. wg.Wait()
  850. close(guard)
  851. if copyError != nil {
  852. return copyError
  853. }
  854. sort.Slice(completedParts, func(i, j int) bool {
  855. return completedParts[i].PartNumber < completedParts[j].PartNumber
  856. })
  857. completeCtx, completeCancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  858. defer completeCancelFn()
  859. _, err = fs.svc.CompleteMultipartUpload(completeCtx, &s3.CompleteMultipartUploadInput{
  860. Bucket: aws.String(fs.config.Bucket),
  861. Key: aws.String(target),
  862. UploadId: aws.String(uploadID),
  863. MultipartUpload: &types.CompletedMultipartUpload{
  864. Parts: completedParts,
  865. },
  866. })
  867. if err != nil {
  868. return fmt.Errorf("unable to complete multipart upload: %w", err)
  869. }
  870. return nil
  871. }
  872. func (fs *S3Fs) getPrefix(name string) string {
  873. prefix := ""
  874. if name != "" && name != "." && name != "/" {
  875. prefix = strings.TrimPrefix(name, "/")
  876. if !strings.HasSuffix(prefix, "/") {
  877. prefix += "/"
  878. }
  879. }
  880. return prefix
  881. }
  882. func (fs *S3Fs) headObject(name string) (*s3.HeadObjectOutput, error) {
  883. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  884. defer cancelFn()
  885. obj, err := fs.svc.HeadObject(ctx, &s3.HeadObjectInput{
  886. Bucket: aws.String(fs.config.Bucket),
  887. Key: aws.String(name),
  888. })
  889. metric.S3HeadObjectCompleted(err)
  890. return obj, err
  891. }
  892. // GetMimeType returns the content type
  893. func (fs *S3Fs) GetMimeType(name string) (string, error) {
  894. obj, err := fs.headObject(name)
  895. if err != nil {
  896. return "", err
  897. }
  898. return util.GetStringFromPointer(obj.ContentType), nil
  899. }
  900. // Close closes the fs
  901. func (*S3Fs) Close() error {
  902. return nil
  903. }
  904. // GetAvailableDiskSize returns the available size for the specified path
  905. func (*S3Fs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  906. return nil, ErrStorageSizeUnavailable
  907. }
  908. func (fs *S3Fs) getStorageID() string {
  909. if fs.config.Endpoint != "" {
  910. if !strings.HasSuffix(fs.config.Endpoint, "/") {
  911. return fmt.Sprintf("s3://%v/%v", fs.config.Endpoint, fs.config.Bucket)
  912. }
  913. return fmt.Sprintf("s3://%v%v", fs.config.Endpoint, fs.config.Bucket)
  914. }
  915. return fmt.Sprintf("s3://%v", fs.config.Bucket)
  916. }
  917. func getAWSHTTPClient(timeout int, idleConnectionTimeout time.Duration) *awshttp.BuildableClient {
  918. c := awshttp.NewBuildableClient().
  919. WithDialerOptions(func(d *net.Dialer) {
  920. d.Timeout = 8 * time.Second
  921. }).
  922. WithTransportOptions(func(tr *http.Transport) {
  923. tr.IdleConnTimeout = idleConnectionTimeout
  924. tr.WriteBufferSize = s3TransferBufferSize
  925. tr.ReadBufferSize = s3TransferBufferSize
  926. })
  927. if timeout > 0 {
  928. c = c.WithTimeout(time.Duration(timeout) * time.Second)
  929. }
  930. return c
  931. }
  932. // ideally we should simply use url.PathEscape:
  933. //
  934. // https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/go/example_code/s3/s3_copy_object.go#L65
  935. //
  936. // but this cause issue with some vendors, see #483, the code below is copied from rclone
  937. func pathEscape(in string) string {
  938. var u url.URL
  939. u.Path = in
  940. return strings.ReplaceAll(u.String(), "+", "%2B")
  941. }