Skip to content

SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.

35.1 KB
Raw Blame
package s3

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"sort"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/session"
	v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/s3/s3iface"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
	"github.com/seaweedfs/seaweedfs/weed/filer"
	"github.com/seaweedfs/seaweedfs/weed/glog"
	"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
	"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
	"github.com/seaweedfs/seaweedfs/weed/remote_storage"
	"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
	"github.com/seaweedfs/seaweedfs/weed/util"
	"github.com/seaweedfs/seaweedfs/weed/util/version"
)

func init() {
	remote_storage.RemoteStorageClientMakers["s3"] = new(s3RemoteStorageMaker)
}

type s3RemoteStorageMaker struct{}

func (s s3RemoteStorageMaker) HasBucket() bool {
	return true
}

func (s s3RemoteStorageMaker) Make(conf *remote_pb.RemoteConf) (remote_storage.RemoteStorageClient, error) {
	return MakeWithHTTPClient(conf, nil)
}

// s3CompatibleOptions carries the per-provider AWS SDK knobs the shared client
// builder needs. Every S3-SDK-backed provider (s3 plus the wasabi/b2/... family)
// converges on the same s3RemoteStorageClient and dials a caller-supplied
// endpoint, differing only in which RemoteConf fields it reads.
type s3CompatibleOptions struct {
	name           string
	endpoint       string
	region         string
	accessKey      string
	secretKey      string
	forcePathStyle bool
	signV4         bool
	// anonymousWhenNoCreds disables SigV4 signing for public buckets when no
	// credentials are supplied. Only the generic "s3" provider does this.
	anonymousWhenNoCreds bool
	// setUserAgent adds the SeaweedFS User-Agent header (generic "s3" only).
	setUserAgent bool
}

// s3CompatibleClientOptions returns the client knobs for an S3-SDK-backed
// RemoteConf and whether conf is such a type. Keeping the type-to-fields
// mapping in one place lets the client builder and the SSRF endpoint guard
// agree on exactly which endpoint each provider dials.
func s3CompatibleClientOptions(conf *remote_pb.RemoteConf) (s3CompatibleOptions, bool) {
	switch conf.Type {
	case "s3":
		return s3CompatibleOptions{
			name:                 "s3",
			endpoint:             conf.S3Endpoint,
			region:               conf.S3Region,
			accessKey:            conf.S3AccessKey,
			secretKey:            conf.S3SecretKey,
			forcePathStyle:       conf.S3ForcePathStyle,
			signV4:               conf.S3V4Signature,
			anonymousWhenNoCreds: true,
			setUserAgent:         true,
		}, true
	case "aliyun":
		return s3CompatibleOptions{
			name:      "aliyun",
			endpoint:  conf.AliyunEndpoint,
			region:    conf.AliyunRegion,
			accessKey: util.Nvl(conf.AliyunAccessKey, os.Getenv("ALICLOUD_ACCESS_KEY_ID")),
			secretKey: util.Nvl(conf.AliyunSecretKey, os.Getenv("ALICLOUD_ACCESS_KEY_SECRET")),
		}, true
	case "b2":
		return s3CompatibleOptions{
			name:           "backblaze",
			endpoint:       conf.BackblazeEndpoint,
			region:         conf.BackblazeRegion,
			accessKey:      conf.BackblazeKeyId,
			secretKey:      conf.BackblazeApplicationKey,
			forcePathStyle: true,
		}, true
	case "baidu":
		return s3CompatibleOptions{
			name:      "baidu",
			endpoint:  conf.BaiduEndpoint,
			region:    conf.BaiduRegion,
			accessKey: util.Nvl(conf.BaiduAccessKey, os.Getenv("BDCLOUD_ACCESS_KEY")),
			secretKey: util.Nvl(conf.BaiduSecretKey, os.Getenv("BDCLOUD_SECRET_KEY")),
			signV4:    true,
		}, true
	case "contabo":
		return s3CompatibleOptions{
			name:           "contabo",
			endpoint:       conf.ContaboEndpoint,
			region:         conf.ContaboRegion,
			accessKey:      util.Nvl(conf.ContaboAccessKey, os.Getenv("ACCESS_KEY")),
			secretKey:      util.Nvl(conf.ContaboSecretKey, os.Getenv("SECRET_KEY")),
			forcePathStyle: true,
		}, true
	case "filebase":
		return s3CompatibleOptions{
			name:           "filebase",
			endpoint:       conf.FilebaseEndpoint,
			region:         "us-east-1",
			accessKey:      util.Nvl(conf.FilebaseAccessKey, os.Getenv("AWS_ACCESS_KEY_ID")),
			secretKey:      util.Nvl(conf.FilebaseSecretKey, os.Getenv("AWS_SECRET_ACCESS_KEY")),
			forcePathStyle: true,
			signV4:         true,
		}, true
	case "storj":
		return s3CompatibleOptions{
			name:           "storj",
			endpoint:       conf.StorjEndpoint,
			region:         "us-west-2",
			accessKey:      util.Nvl(conf.StorjAccessKey, os.Getenv("AWS_ACCESS_KEY_ID")),
			secretKey:      util.Nvl(conf.StorjSecretKey, os.Getenv("AWS_SECRET_ACCESS_KEY")),
			forcePathStyle: true,
		}, true
	case "tencent":
		return s3CompatibleOptions{
			name:           "tencent",
			endpoint:       conf.TencentEndpoint,
			region:         "us-west-2",
			accessKey:      util.Nvl(conf.TencentSecretId, os.Getenv("COS_SECRETID")),
			secretKey:      util.Nvl(conf.TencentSecretKey, os.Getenv("COS_SECRETKEY")),
			forcePathStyle: true,
		}, true
	case "wasabi":
		return s3CompatibleOptions{
			name:           "wasabi",
			endpoint:       conf.WasabiEndpoint,
			region:         conf.WasabiRegion,
			accessKey:      conf.WasabiAccessKey,
			secretKey:      conf.WasabiSecretKey,
			forcePathStyle: true,
		}, true
	}
	return s3CompatibleOptions{}, false
}

// S3CompatibleEndpoint returns the endpoint an S3-SDK-backed RemoteConf would
// dial directly, and whether conf is such a type. The volume server validates
// this endpoint against the SSRF deny-list for every S3-compatible provider,
// not just the generic "s3" type.
func S3CompatibleEndpoint(conf *remote_pb.RemoteConf) (string, bool) {
	opt, ok := s3CompatibleClientOptions(conf)
	if !ok {
		return "", false
	}
	return opt.endpoint, true
}

// UsesDefaultCredentialChain reports whether a client of conf, of any
// S3-compatible type, may take its credentials from the SDK's default chain
// (an access key or a secret missing, after the type's own environment
// fallbacks): the only case where they live outside the configuration.
func UsesDefaultCredentialChain(conf *remote_pb.RemoteConf) bool {
	opt, ok := s3CompatibleClientOptions(conf)
	return ok && !(opt.accessKey != "" && opt.secretKey != "")
}

// ResolvedCredentials returns the static credentials a client of conf carries
// — the configuration's own keys, or the type's environment fallback for an
// unset field — and whether conf is S3-compatible at all. An environment
// fallback's change shows up here where the configuration's hash would not.
func ResolvedCredentials(conf *remote_pb.RemoteConf) (accessKey, secretKey string, ok bool) {
	opt, ok := s3CompatibleClientOptions(conf)
	return opt.accessKey, opt.secretKey, ok
}

// awsCredentialSourceConfigured reports whether the environment names a source
// for the AWS SDK default credential chain, such as static keys, a profile,
// IRSA web identity or the ECS/EKS container credentials endpoint.
func awsCredentialSourceConfigured() bool {
	for _, name := range []string{
		"AWS_ACCESS_KEY_ID",
		"AWS_PROFILE",
		"AWS_DEFAULT_PROFILE",
		"AWS_WEB_IDENTITY_TOKEN_FILE",
		"AWS_CONTAINER_CREDENTIALS_FULL_URI",
		"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
		"AWS_SHARED_CREDENTIALS_FILE",
		"AWS_CONFIG_FILE",
	} {
		if os.Getenv(name) != "" {
			return true
		}
	}
	return false
}

// MakeWithHTTPClient builds the client for any S3-SDK-backed remote storage
// type using the supplied *http.Client (or the AWS SDK default when nil).
// Callers that need to pin the dial path against DNS rebinding can pass a
// client whose transport has a guarded DialContext.
func MakeWithHTTPClient(conf *remote_pb.RemoteConf, httpClient *http.Client) (remote_storage.RemoteStorageClient, error) {
	opt, ok := s3CompatibleClientOptions(conf)
	if !ok {
		return nil, fmt.Errorf("%q is not an S3-compatible remote storage type", conf.Type)
	}
	client := &s3RemoteStorageClient{
		conf: conf,
	}
	config := &aws.Config{
		Region:                        aws.String(opt.region),
		Endpoint:                      aws.String(opt.endpoint),
		S3ForcePathStyle:              aws.Bool(opt.forcePathStyle),
		S3DisableContentMD5Validation: aws.Bool(true),
	}
	if httpClient != nil {
		config.HTTPClient = httpClient
	}
	if opt.accessKey != "" && opt.secretKey != "" {
		config.Credentials = credentials.NewStaticCredentials(opt.accessKey, opt.secretKey, "")
	} else if opt.anonymousWhenNoCreds && opt.accessKey == "" && opt.secretKey == "" && !awsCredentialSourceConfigured() {
		// Explicitly disable signing for public buckets. When the environment
		// names an AWS credential source, leave Credentials nil so the SDK
		// default chain (env, web identity, container, shared profile) is used.
		config.Credentials = credentials.AnonymousCredentials
	} else if config.Credentials == nil && config.HTTPClient != nil {
		// Remote credential providers (container endpoints, IMDS, web
		// identity) fetch through this HTTP client; the guarded one is for the
		// S3 endpoint and blocks the link-local credential endpoints, so the
		// default chain resolves on an unguarded client. Shared config stays
		// enabled so web identity and profiles resolve here too, and the
		// region carries over so STS can sign assume-role requests.
		credSess, err := session.NewSessionWithOptions(session.Options{
			Config:            aws.Config{Region: config.Region, HTTPClient: &http.Client{}},
			SharedConfigState: session.SharedConfigEnable,
		})
		if err != nil {
			return nil, fmt.Errorf("create %s credential session: %w", opt.name, err)
		}
		config.Credentials = credSess.Config.Credentials
	}

	sess, err := session.NewSessionWithOptions(session.Options{
		Config:            *config,
		SharedConfigState: session.SharedConfigEnable,
	})
	if err != nil {
		return nil, fmt.Errorf("create %s session: %w", opt.name, err)
	}
	if opt.signV4 {
		sess.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
	}
	if opt.setUserAgent {
		sess.Handlers.Build.PushBack(func(r *request.Request) {
			r.HTTPRequest.Header.Set("User-Agent", "SeaweedFS/"+version.VERSION_NUMBER)
		})
	}
	sess.Handlers.Build.PushFront(skipSha256PayloadSigning)
	client.conn = s3.New(sess)
	return client, nil
}

var skipSha256PayloadSigning = func(r *request.Request) {
	// see https://github.com/ceph/ceph/pull/15965/files
	if r.ClientInfo.ServiceID != "S3" {
		return
	}
	if r.Operation.Name == "PutObject" || r.Operation.Name == "UploadPart" {
		if len(r.HTTPRequest.Header.Get("X-Amz-Content-Sha256")) == 0 {
			r.HTTPRequest.Header.Set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD")
		}
	}
}

type s3RemoteStorageClient struct {
	conf *remote_pb.RemoteConf
	conn s3iface.S3API
}

const (
	defaultUploadConcurrency = 1
	defaultReadConcurrency   = 5
)

func (s *s3RemoteStorageClient) uploadConcurrency() int {
	if n := int(s.conf.GetUploadConcurrency()); n > 0 {
		return n
	}
	return defaultUploadConcurrency
}

func (s *s3RemoteStorageClient) downloadConcurrency() int {
	if n := int(s.conf.GetDownloadConcurrency()); n > 0 {
		return n
	}
	return defaultReadConcurrency
}

var _ = remote_storage.RemoteStorageClient(&s3RemoteStorageClient{})

func (s *s3RemoteStorageClient) Traverse(remote *remote_pb.RemoteStorageLocation, visitFn remote_storage.VisitFunc) (err error) {

	pathKey := remote.Path[1:]

	listInput := &s3.ListObjectsV2Input{
		Bucket:              aws.String(remote.Bucket),
		ContinuationToken:   nil,
		Delimiter:           nil, // not aws.String("/"), iterate through all entries
		EncodingType:        nil,
		ExpectedBucketOwner: nil,
		FetchOwner:          nil,
		MaxKeys:             nil, // aws.Int64(1000),
		Prefix:              aws.String(pathKey),
		RequestPayer:        nil,
		StartAfter:          nil,
	}
	isLastPage := false
	for !isLastPage && err == nil {
		var localErr error
		listErr := s.conn.ListObjectsV2Pages(listInput, func(page *s3.ListObjectsV2Output, lastPage bool) bool {
			for _, content := range page.Contents {
				key := *content.Key
				key = "/" + key
				dir, name := util.FullPath(key).DirAndName()
				remoteEntry := &filer_pb.RemoteEntry{
					StorageName: s.conf.Name,
				}
				if content.LastModified != nil {
					remoteEntry.RemoteMtime = content.LastModified.Unix()
				}
				if content.Size != nil {
					remoteEntry.RemoteSize = *content.Size
				}
				if content.ETag != nil {
					remoteEntry.RemoteETag = *content.ETag
				}
				if err := visitFn(dir, name, false, remoteEntry); err != nil {
					localErr = err
					return false
				}
			}
			listInput.ContinuationToken = page.NextContinuationToken
			isLastPage = lastPage
			return true
		})
		if listErr != nil {
			err = fmt.Errorf("list %v: %w", remote, listErr)
		}
		if localErr != nil {
			err = fmt.Errorf("process %v: %w", remote, localErr)
		}
	}
	return
}

func (s *s3RemoteStorageClient) ListDirectory(ctx context.Context, loc *remote_pb.RemoteStorageLocation, visitFn remote_storage.VisitFunc) error {
	pathKey := loc.Path[1:]
	if pathKey != "" && !strings.HasSuffix(pathKey, "/") {
		pathKey += "/"
	}

	listInput := &s3.ListObjectsV2Input{
		Bucket:    aws.String(loc.Bucket),
		Prefix:    aws.String(pathKey),
		Delimiter: aws.String("/"),
	}

	var localErr error
	listErr := s.conn.ListObjectsV2PagesWithContext(ctx, listInput, func(page *s3.ListObjectsV2Output, lastPage bool) bool {
		for _, prefix := range page.CommonPrefixes {
			if prefix.Prefix == nil {
				continue
			}
			dirKey := "/" + strings.TrimSuffix(*prefix.Prefix, "/")
			dir, name := util.FullPath(dirKey).DirAndName()
			if err := visitFn(dir, name, true, nil); err != nil {
				localErr = err
				return false
			}
		}
		for _, content := range page.Contents {
			key := "/" + *content.Key
			if strings.HasSuffix(key, "/") {
				continue // skip directory markers
			}
			dir, name := util.FullPath(key).DirAndName()
			remoteEntry := &filer_pb.RemoteEntry{
				StorageName: s.conf.Name,
			}
			if content.LastModified != nil {
				remoteEntry.RemoteMtime = content.LastModified.Unix()
			}
			if content.Size != nil {
				remoteEntry.RemoteSize = *content.Size
			}
			if content.ETag != nil {
				remoteEntry.RemoteETag = *content.ETag
			}
			if err := visitFn(dir, name, false, remoteEntry); err != nil {
				localErr = err
				return false
			}
		}
		return true
	})
	if listErr != nil {
		return fmt.Errorf("list directory %v: %w", loc, listErr)
	}
	if localErr != nil {
		return fmt.Errorf("process directory %v: %w", loc, localErr)
	}
	return nil
}

func (s *s3RemoteStorageClient) StatFile(loc *remote_pb.RemoteStorageLocation) (remoteEntry *filer_pb.RemoteEntry, err error) {
	resp, err := s.conn.HeadObject(&s3.HeadObjectInput{
		Bucket: aws.String(loc.Bucket),
		Key:    aws.String(loc.Path[1:]),
	})
	if err != nil {
		if reqErr, ok := err.(awserr.RequestFailure); ok && reqErr.StatusCode() == http.StatusNotFound {
			return nil, remote_storage.ErrRemoteObjectNotFound
		}
		return nil, fmt.Errorf("stat s3 %s%s: %w", loc.Bucket, loc.Path, err)
	}
	remoteEntry = &filer_pb.RemoteEntry{
		StorageName: s.conf.Name,
	}
	if resp.ContentLength != nil {
		remoteEntry.RemoteSize = *resp.ContentLength
	}
	if resp.LastModified != nil {
		remoteEntry.RemoteMtime = resp.LastModified.Unix()
	}
	if resp.ETag != nil {
		remoteEntry.RemoteETag = *resp.ETag
	}
	// a HeadObject response is authoritative: no header means no encoding
	remoteEntry.RemoteContentEncoding = aws.String(aws.StringValue(resp.ContentEncoding))
	return remoteEntry, nil
}

func (s *s3RemoteStorageClient) ReadFile(loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (data []byte, err error) {
	return s.ReadFileWithConcurrency(loc, offset, size, 0)
}

func (s *s3RemoteStorageClient) ReadFileWithConcurrency(loc *remote_pb.RemoteStorageLocation, offset int64, size int64, concurrency int) (data []byte, err error) {
	if concurrency <= 0 {
		concurrency = s.downloadConcurrency()
	}
	downloader := s3manager.NewDownloaderWithClient(s.conn, func(u *s3manager.Downloader) {
		u.PartSize = int64(4 * 1024 * 1024)
		u.Concurrency = concurrency
	})

	dataSlice := make([]byte, int(size))
	writerAt := aws.NewWriteAtBuffer(dataSlice)

	n, err := downloader.Download(writerAt, &s3.GetObjectInput{
		Bucket: aws.String(loc.Bucket),
		Key:    aws.String(loc.Path[1:]),
		Range:  aws.String(fmt.Sprintf("bytes=%d-%d", offset, offset+size-1)),
	})
	if err != nil {
		if isNoSuchKey(err) {
			return nil, remote_storage.ErrRemoteObjectNotFound
		}
		return nil, fmt.Errorf("failed to download file %s%s: %v", loc.Bucket, loc.Path, err)
	}
	// The buffer is pre-sized to size, so a short read leaves the tail
	// zero-padded and would be cached as valid-looking but corrupt content.
	// Reject it instead.
	if n != size {
		return nil, fmt.Errorf("short read from %s%s at offset %d: got %d bytes, want %d", loc.Bucket, loc.Path, offset, n, size)
	}

	return writerAt.Bytes(), nil
}

func (s *s3RemoteStorageClient) ReadFileAsStream(ctx context.Context, loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (reader io.ReadCloser, err error) {
	output, err := s.conn.GetObjectWithContext(ctx, &s3.GetObjectInput{
		Bucket: aws.String(loc.Bucket),
		Key:    aws.String(loc.Path[1:]),
		Range:  aws.String(fmt.Sprintf("bytes=%d-%d", offset, offset+size-1)),
	})
	if err != nil {
		if isNoSuchKey(err) {
			return nil, remote_storage.ErrRemoteObjectNotFound
		}
		return nil, fmt.Errorf("failed to open stream for %s%s: %v", loc.Bucket, loc.Path, err)
	}
	return output.Body, nil
}

// isNoSuchKey matches only a missing key: a missing bucket is also a 404 but
// says nothing about the object.
func isNoSuchKey(err error) bool {
	var aerr awserr.Error
	return errors.As(err, &aerr) && aerr.Code() == s3.ErrCodeNoSuchKey
}

func (s *s3RemoteStorageClient) WriteDirectory(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry) (err error) {
	return nil
}

func (s *s3RemoteStorageClient) RemoveDirectory(loc *remote_pb.RemoteStorageLocation) (err error) {
	// the trailing slash keeps sibling prefixes that share the name intact
	prefix := loc.Path[1:]
	if prefix != "" && !strings.HasSuffix(prefix, "/") {
		prefix += "/"
	}
	if prefix == "" {
		// the mount root maps to the whole bucket; wiping every object from a
		// single namespace event is too destructive, so keep them
		glog.Warningf("s3 %s: skip removing directory mapped to the bucket root", loc.Bucket)
		return nil
	}

	listInput := &s3.ListObjectsV2Input{
		Bucket: aws.String(loc.Bucket),
		Prefix: aws.String(prefix),
	}
	var deleteErr error
	listErr := s.conn.ListObjectsV2Pages(listInput, func(page *s3.ListObjectsV2Output, lastPage bool) bool {
		var objects []*s3.ObjectIdentifier
		for _, content := range page.Contents {
			objects = append(objects, &s3.ObjectIdentifier{Key: content.Key})
		}
		if len(objects) == 0 {
			return true
		}
		// a listing page holds at most 1000 keys, the DeleteObjects limit
		req, resp := s.conn.DeleteObjectsRequest(&s3.DeleteObjectsInput{
			Bucket: aws.String(loc.Bucket),
			Delete: &s3.Delete{
				Objects: objects,
				Quiet:   aws.Bool(true),
			},
		})
		// the client-level S3DisableContentMD5Validation also drops the
		// Content-MD5 header this operation requires; the request config is a
		// copy, so re-enabling it here leaves other operations untouched
		req.Config.S3DisableContentMD5Validation = aws.Bool(false)
		batchErr := req.Send()
		if batchErr != nil {
			deleteErr = batchErr
			return false
		}
		if len(resp.Errors) > 0 {
			// a batch can fail 1000 keys; report the scope, not every key
			failed := resp.Errors[0]
			deleteErr = fmt.Errorf("%d keys failed, first is %s: %s %s", len(resp.Errors), aws.StringValue(failed.Key), aws.StringValue(failed.Code), aws.StringValue(failed.Message))
			return false
		}
		return true
	})
	if listErr != nil {
		return fmt.Errorf("list %s/%s: %w", loc.Bucket, prefix, listErr)
	}
	if deleteErr != nil {
		return fmt.Errorf("remove directory %s/%s: %w", loc.Bucket, prefix, deleteErr)
	}
	return nil
}

func (s *s3RemoteStorageClient) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (remoteEntry *filer_pb.RemoteEntry, err error) {

	fileSize := int64(filer.FileSize(entry))

	partSize := int64(8 * 1024 * 1024) // The minimum/default allowed part size is 5MB
	for partSize*1000 < fileSize {
		partSize *= 4
	}

	// Create an uploader with the session and custom options
	uploader := s3manager.NewUploaderWithClient(s.conn, func(u *s3manager.Uploader) {
		u.PartSize = partSize
		u.Concurrency = s.uploadConcurrency()
	})

	var awsTags *string
	// openstack swift doesn't support s3 object tagging
	if s.conf.S3SupportTagging {
		if tagging := toTagging(entry.Extended); len(tagging.TagSet) > 0 {
			awsTags = aws.String(s3TaggingHeader(tagging.TagSet))
		}
	}

	// Upload the file to S3.
	uploadInput := &s3manager.UploadInput{
		Bucket:  aws.String(loc.Bucket),
		Key:     aws.String(loc.Path[1:]),
		Body:    reader,
		Tagging: awsTags,
	}
	if entry.Attributes != nil && entry.Attributes.Mime != "" {
		uploadInput.ContentType = aws.String(entry.Attributes.Mime)
	}
	if contentEncoding := remote_storage.EntryContentEncoding(entry); contentEncoding != "" {
		uploadInput.ContentEncoding = aws.String(contentEncoding)
	}
	if s.conf.S3StorageClass != "" {
		uploadInput.StorageClass = aws.String(s.conf.S3StorageClass)
	}
	_, err = uploader.Upload(uploadInput)

	//in case it fails to upload
	if err != nil {
		return nil, fmt.Errorf("upload to %s/%s%s: %v", loc.Name, loc.Bucket, loc.Path, err)
	}

	// read back the remote entry
	return s.readFileRemoteEntry(loc)

}

// toTagging maps the entry's extended attributes to the remote object's tag
// set. Only X-Amz-Tagging-* attributes are S3 tags; the rest of Extended is
// Seaweed-internal metadata whose values are not legal tag values.
func toTagging(attributes map[string][]byte) *s3.Tagging {
	tagging := &s3.Tagging{}
	for k, v := range attributes {
		if !strings.HasPrefix(k, s3_constants.AmzObjectTaggingPrefix) {
			continue
		}
		tagging.TagSet = append(tagging.TagSet, &s3.Tag{
			Key:   aws.String(k[len(s3_constants.AmzObjectTaggingPrefix):]),
			Value: aws.String(string(v)),
		})
	}
	sort.Slice(tagging.TagSet, func(i, j int) bool {
		return aws.StringValue(tagging.TagSet[i].Key) < aws.StringValue(tagging.TagSet[j].Key)
	})
	return tagging
}

func (s *s3RemoteStorageClient) readFileRemoteEntry(loc *remote_pb.RemoteStorageLocation) (*filer_pb.RemoteEntry, error) {
	return s.StatFile(loc)
}

// the largest object a single CopyObject call accepts
const s3CopyObjectSizeLimit = 5 * 1024 * 1024 * 1024

func (s *s3RemoteStorageClient) UpdateFileMetadata(loc *remote_pb.RemoteStorageLocation, oldEntry *filer_pb.Entry, newEntry *filer_pb.Entry) (remoteEntry *filer_pb.RemoteEntry, err error) {
	if reflect.DeepEqual(oldEntry.Extended, newEntry.Extended) {
		return nil, nil
	}

	// Content-Encoding is S3 system metadata, changeable without a content
	// rewrite only through an in-place copy
	if encoding := remote_storage.EntryContentEncoding(newEntry); encoding != remote_storage.EntryContentEncoding(oldEntry) {
		key := loc.Path[1:]
		if fileSize := int64(filer.FileSize(newEntry)); fileSize > s3CopyObjectSizeLimit {
			glog.Warningf("s3 %s/%s: applying the Content-Encoding change needs an object copy, but %d bytes exceeds the copy limit; it will apply on the next content write", loc.Bucket, key, fileSize)
		} else {
			// the replace directive drops everything not resent, so read the
			// object's current metadata and carry it over
			headOut, headErr := s.conn.HeadObject(&s3.HeadObjectInput{
				Bucket: aws.String(loc.Bucket),
				Key:    aws.String(key),
			})
			if headErr != nil {
				return nil, fmt.Errorf("stat %s/%s before metadata copy: %w", loc.Bucket, key, headErr)
			}
			copyInput := &s3.CopyObjectInput{
				Bucket:                  aws.String(loc.Bucket),
				Key:                     aws.String(key),
				CopySource:              aws.String(s3CopySource(loc.Bucket, key)),
				MetadataDirective:       aws.String(s3.MetadataDirectiveReplace),
				Metadata:                headOut.Metadata,
				ContentType:             headOut.ContentType,
				CacheControl:            headOut.CacheControl,
				ContentDisposition:      headOut.ContentDisposition,
				ContentLanguage:         headOut.ContentLanguage,
				WebsiteRedirectLocation: headOut.WebsiteRedirectLocation,
				ServerSideEncryption:    headOut.ServerSideEncryption,
				SSEKMSKeyId:             headOut.SSEKMSKeyId,
				StorageClass:            headOut.StorageClass,
			}
			if headOut.Expires != nil {
				if expires, parseErr := http.ParseTime(*headOut.Expires); parseErr == nil {
					copyInput.Expires = aws.Time(expires)
				}
			}
			if encoding != "" {
				copyInput.ContentEncoding = aws.String(encoding)
			}
			if newEntry.Attributes != nil && newEntry.Attributes.Mime != "" {
				copyInput.ContentType = aws.String(newEntry.Attributes.Mime)
			}
			if s.conf.S3StorageClass != "" {
				copyInput.StorageClass = aws.String(s.conf.S3StorageClass)
			}
			copyOutput, copyErr := s.conn.CopyObject(copyInput)
			if copyErr != nil {
				return nil, fmt.Errorf("update content encoding of %s/%s: %w", loc.Bucket, key, copyErr)
			}
			// the copy rewrites the object and can mint a new ETag, so the
			// stamp it produced is reported instead of a fresh stat — which
			// could describe a replacement that landed in between
			remoteEntry = &filer_pb.RemoteEntry{
				StorageName: s.conf.Name,
				RemoteSize:  aws.Int64Value(headOut.ContentLength),
			}
			if result := copyOutput.CopyObjectResult; result != nil {
				remoteEntry.RemoteETag = aws.StringValue(result.ETag)
				if result.LastModified != nil {
					remoteEntry.RemoteMtime = result.LastModified.Unix()
				}
			}
			if encoding != "" {
				remoteEntry.RemoteContentEncoding = aws.String(encoding)
			}
		}
	}

	// same as the write path: a remote without tagging support rejects both
	// PutObjectTagging and DeleteObjectTagging
	if !s.conf.S3SupportTagging {
		return
	}

	tagging := toTagging(newEntry.Extended)
	if reflect.DeepEqual(tagging.TagSet, toTagging(oldEntry.Extended).TagSet) {
		return
	}
	if len(tagging.TagSet) > 0 {
		_, err = s.conn.PutObjectTagging(&s3.PutObjectTaggingInput{
			Bucket:  aws.String(loc.Bucket),
			Key:     aws.String(loc.Path[1:]),
			Tagging: tagging,
		})
	} else {
		_, err = s.conn.DeleteObjectTagging(&s3.DeleteObjectTaggingInput{
			Bucket: aws.String(loc.Bucket),
			Key:    aws.String(loc.Path[1:]),
		})
	}
	if err != nil {
		return nil, err
	}
	return
}

// s3CopyPartSize is the smallest part a multipart copy uses; parts grow so
// the largest object stays within the 10000-part limit
const s3CopyPartSize = 512 * 1024 * 1024

// CopyFile copies the object at src to dst on the server side, with a single
// CopyObject up to the 5 GB limit and a multipart copy above it. The copy
// keeps the source's metadata.
func (s *s3RemoteStorageClient) CopyFile(src *remote_pb.RemoteStorageLocation, dst *remote_pb.RemoteStorageLocation) (remoteEntry *filer_pb.RemoteEntry, err error) {
	srcKey, dstKey := src.Path[1:], dst.Path[1:]
	headOut, err := s.conn.HeadObject(&s3.HeadObjectInput{
		Bucket: aws.String(src.Bucket),
		Key:    aws.String(srcKey),
	})
	if err != nil {
		if reqErr, ok := err.(awserr.RequestFailure); ok && reqErr.StatusCode() == http.StatusNotFound {
			return nil, remote_storage.ErrRemoteObjectNotFound
		}
		return nil, fmt.Errorf("stat s3 %s/%s before copy: %w", src.Bucket, srcKey, err)
	}
	copySource := aws.String(s3CopySource(src.Bucket, srcKey))
	var storageClass *string
	if s.conf.S3StorageClass != "" {
		storageClass = aws.String(s.conf.S3StorageClass)
	}

	if size := aws.Int64Value(headOut.ContentLength); size <= s3CopyObjectSizeLimit {
		// a copy takes the bucket's default encryption unless told otherwise
		if _, err = s.conn.CopyObject(&s3.CopyObjectInput{
			Bucket:               aws.String(dst.Bucket),
			Key:                  aws.String(dstKey),
			CopySource:           copySource,
			StorageClass:         storageClass,
			ServerSideEncryption: headOut.ServerSideEncryption,
			SSEKMSKeyId:          headOut.SSEKMSKeyId,
		}); err != nil {
			return nil, fmt.Errorf("copy s3 %s/%s to %s/%s: %w", src.Bucket, srcKey, dst.Bucket, dstKey, err)
		}
	} else if err = s.multipartCopy(headOut, src, copySource, size, dst.Bucket, dstKey, storageClass); err != nil {
		return nil, fmt.Errorf("copy s3 %s/%s to %s/%s: %w", src.Bucket, srcKey, dst.Bucket, dstKey, err)
	}

	return s.readFileRemoteEntry(dst)
}

// s3CopySource escapes each segment of the copy source and keeps the slashes,
// which every S3 implementation reads back
func s3CopySource(bucket, key string) string {
	segments := strings.Split(bucket+"/"+key, "/")
	for i, segment := range segments {
		segments[i] = url.PathEscape(segment)
	}
	return strings.Join(segments, "/")
}

// s3TaggingHeader encodes tags as the query string x-amz-tagging takes, with
// spaces as %20: a + is read back as a space by some implementations and
// literally by others
func s3TaggingHeader(tagSet []*s3.Tag) string {
	escape := func(s string) string {
		return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
	}
	pairs := make([]string, 0, len(tagSet))
	for _, tag := range tagSet {
		pairs = append(pairs, escape(aws.StringValue(tag.Key))+"="+escape(aws.StringValue(tag.Value)))
	}
	return strings.Join(pairs, "&")
}

// multipartCopy copies an object above the CopyObject limit part by part. A
// multipart upload does not inherit the source's metadata or tags, so they are
// carried over like CopyObject would: metadata from the source's HeadObject,
// tags when the remote supports tagging.
func (s *s3RemoteStorageClient) multipartCopy(headOut *s3.HeadObjectOutput, src *remote_pb.RemoteStorageLocation, copySource *string, size int64, bucket, key string, storageClass *string) error {
	createInput := &s3.CreateMultipartUploadInput{
		Bucket:                  aws.String(bucket),
		Key:                     aws.String(key),
		Metadata:                headOut.Metadata,
		ContentType:             headOut.ContentType,
		ContentEncoding:         headOut.ContentEncoding,
		CacheControl:            headOut.CacheControl,
		ContentDisposition:      headOut.ContentDisposition,
		ContentLanguage:         headOut.ContentLanguage,
		WebsiteRedirectLocation: headOut.WebsiteRedirectLocation,
		ServerSideEncryption:    headOut.ServerSideEncryption,
		SSEKMSKeyId:             headOut.SSEKMSKeyId,
		StorageClass:            storageClass,
	}
	if headOut.Expires != nil {
		if expires, parseErr := http.ParseTime(*headOut.Expires); parseErr == nil {
			createInput.Expires = aws.Time(expires)
		}
	}
	if s.conf.S3SupportTagging {
		tagOut, tagErr := s.conn.GetObjectTagging(&s3.GetObjectTaggingInput{
			Bucket: aws.String(src.Bucket),
			Key:    aws.String(src.Path[1:]),
		})
		if tagErr != nil {
			return fmt.Errorf("read tags: %w", tagErr)
		}
		if len(tagOut.TagSet) > 0 {
			createInput.Tagging = aws.String(s3TaggingHeader(tagOut.TagSet))
		}
	}
	createOut, err := s.conn.CreateMultipartUpload(createInput)
	if err != nil {
		return err
	}

	partSize := int64(s3CopyPartSize)
	for partSize*10000 < size {
		partSize *= 2
	}
	var parts []*s3.CompletedPart
	for offset, partNumber := int64(0), int64(1); offset < size; offset, partNumber = offset+partSize, partNumber+1 {
		partOut, partErr := s.conn.UploadPartCopy(&s3.UploadPartCopyInput{
			Bucket:          aws.String(bucket),
			Key:             aws.String(key),
			UploadId:        createOut.UploadId,
			PartNumber:      aws.Int64(partNumber),
			CopySource:      copySource,
			CopySourceRange: aws.String(fmt.Sprintf("bytes=%d-%d", offset, min(offset+partSize, size)-1)),
			// every part from the object the HeadObject saw, not a mix of
			// versions if it is overwritten mid-copy
			CopySourceIfMatch: headOut.ETag,
		})
		if partErr == nil && partOut.CopyPartResult == nil {
			partErr = errors.New("no part result")
		}
		if partErr != nil {
			s.abortMultipartUpload(bucket, key, createOut.UploadId)
			return fmt.Errorf("copy part %d: %w", partNumber, partErr)
		}
		parts = append(parts, &s3.CompletedPart{
			ETag:       partOut.CopyPartResult.ETag,
			PartNumber: aws.Int64(partNumber),
		})
	}

	if _, err = s.conn.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
		Bucket:          aws.String(bucket),
		Key:             aws.String(key),
		UploadId:        createOut.UploadId,
		MultipartUpload: &s3.CompletedMultipartUpload{Parts: parts},
	}); err != nil {
		s.abortMultipartUpload(bucket, key, createOut.UploadId)
		return err
	}
	return nil
}

func (s *s3RemoteStorageClient) abortMultipartUpload(bucket, key string, uploadId *string) {
	if _, err := s.conn.AbortMultipartUpload(&s3.AbortMultipartUploadInput{
		Bucket:   aws.String(bucket),
		Key:      aws.String(key),
		UploadId: uploadId,
	}); err != nil {
		glog.Warningf("abort multipart copy to s3 %s/%s: %v", bucket, key, err)
	}
}

func (s *s3RemoteStorageClient) DeleteFile(loc *remote_pb.RemoteStorageLocation) (err error) {
	_, err = s.conn.DeleteObject(&s3.DeleteObjectInput{
		Bucket: aws.String(loc.Bucket),
		Key:    aws.String(loc.Path[1:]),
	})
	return
}

// DeleteFileIfUnchanged deletes the object only while it is still the one the
// stat describes, enforced with the S3 conditional-delete If-Match header. A
// replacement that lands between the stat and the delete fails the
// precondition instead of being deleted.
func (s *s3RemoteStorageClient) DeleteFileIfUnchanged(loc *remote_pb.RemoteStorageLocation, stamp *filer_pb.RemoteEntry) (bool, error) {
	live, err := s.StatFile(loc)
	if err != nil {
		if errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
			return true, nil
		}
		return false, err
	}
	if !remote_storage.StillCurrent(stamp, live) {
		return false, nil
	}
	if live.RemoteETag == "" {
		return true, s.DeleteFile(loc)
	}
	req, _ := s.conn.DeleteObjectRequest(&s3.DeleteObjectInput{
		Bucket: aws.String(loc.Bucket),
		Key:    aws.String(loc.Path[1:]),
	})
	req.Handlers.Build.PushBack(func(r *request.Request) {
		r.HTTPRequest.Header.Set("If-Match", live.RemoteETag)
	})
	if err := req.Send(); err != nil {
		if reqErr, ok := err.(awserr.RequestFailure); ok {
			switch reqErr.StatusCode() {
			case http.StatusPreconditionFailed:
				return false, nil
			case http.StatusNotFound:
				return true, nil
			}
		}
		return false, fmt.Errorf("delete s3 %s%s: %w", loc.Bucket, loc.Path, err)
	}
	return true, nil
}

func (s *s3RemoteStorageClient) ListBuckets() (buckets []*remote_storage.Bucket, err error) {
	resp, err := s.conn.ListBuckets(&s3.ListBucketsInput{})
	if err != nil {
		return nil, fmt.Errorf("list buckets: %w", err)
	}
	for _, b := range resp.Buckets {
		buckets = append(buckets, &remote_storage.Bucket{
			Name:      *b.Name,
			CreatedAt: *b.CreationDate,
		})
	}
	return
}

func (s *s3RemoteStorageClient) CreateBucket(name string) (err error) {
	_, err = s.conn.CreateBucket(&s3.CreateBucketInput{
		ACL:                        nil,
		Bucket:                     aws.String(name),
		CreateBucketConfiguration:  nil,
		GrantFullControl:           nil,
		GrantRead:                  nil,
		GrantReadACP:               nil,
		GrantWrite:                 nil,
		GrantWriteACP:              nil,
		ObjectLockEnabledForBucket: nil,
	})
	if err != nil {
		return fmt.Errorf("%s create bucket %s: %v", s.conf.Name, name, err)
	}
	return
}

func (s *s3RemoteStorageClient) DeleteBucket(name string) (err error) {
	_, err = s.conn.DeleteBucket(&s3.DeleteBucketInput{
		Bucket: aws.String(name),
	})
	if err != nil {
		var aerr awserr.Error
		if errors.As(err, &aerr) && aerr.Code() == s3.ErrCodeNoSuchBucket {
			return nil
		}
		return fmt.Errorf("delete bucket %s: %v", name, err)
	}
	return
}