s3fs.go 30 KB

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