1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 "git.arvados.org/arvados.git/sdk/go/arvados"
27 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
28 "git.arvados.org/arvados.git/sdk/go/ctxlog"
29 "git.arvados.org/arvados.git/sdk/go/keepclient"
30 "github.com/AdRoll/goamz/s3"
35 s3SignAlgorithm = "AWS4-HMAC-SHA256"
36 s3MaxClockSkew = 5 * time.Minute
39 type commonPrefix struct {
43 type listV1Resp struct {
44 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
46 // s3.ListResp marshals an empty tag when
47 // CommonPrefixes is nil, which confuses some clients.
48 // Fix by using this nested struct instead.
49 CommonPrefixes []commonPrefix
50 // Similarly, we need omitempty here, because an empty
51 // tag confuses some clients (e.g.,
52 // github.com/aws/aws-sdk-net never terminates its
54 NextMarker string `xml:"NextMarker,omitempty"`
55 // ListObjectsV2 has a KeyCount response field.
59 type listV2Resp struct {
60 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
67 CommonPrefixes []commonPrefix
68 EncodingType string `xml:",omitempty"`
70 ContinuationToken string `xml:",omitempty"`
71 NextContinuationToken string `xml:",omitempty"`
72 StartAfter string `xml:",omitempty"`
75 func hmacstring(msg string, key []byte) []byte {
76 h := hmac.New(sha256.New, key)
77 io.WriteString(h, msg)
81 func hashdigest(h hash.Hash, payload string) string {
82 io.WriteString(h, payload)
83 return fmt.Sprintf("%x", h.Sum(nil))
86 // Signing key for given secret key and request attrs.
87 func s3signatureKey(key, datestamp, regionName, serviceName string) []byte {
88 return hmacstring("aws4_request",
89 hmacstring(serviceName,
90 hmacstring(regionName,
91 hmacstring(datestamp, []byte("AWS4"+key)))))
94 // Canonical query string for S3 V4 signature: sorted keys, spaces
95 // escaped as %20 instead of +, keyvalues joined with &.
96 func s3querystring(u *url.URL) string {
97 keys := make([]string, 0, len(u.Query()))
98 values := make(map[string]string, len(u.Query()))
99 for k, vs := range u.Query() {
100 k = strings.Replace(url.QueryEscape(k), "+", "%20", -1)
101 keys = append(keys, k)
102 for _, v := range vs {
103 v = strings.Replace(url.QueryEscape(v), "+", "%20", -1)
107 values[k] += k + "=" + v
111 for i, k := range keys {
114 return strings.Join(keys, "&")
117 var reMultipleSlashChars = regexp.MustCompile(`//+`)
119 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
120 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
122 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
124 t, err := time.Parse(timefmt, timestr)
126 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
128 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
129 return "", errors.New("exceeded max clock skew")
132 var canonicalHeaders string
133 for _, h := range strings.Split(signedHeaders, ";") {
135 canonicalHeaders += h + ":" + r.Host + "\n"
137 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
141 normalizedURL := *r.URL
142 normalizedURL.RawPath = ""
143 normalizedURL.Path = reMultipleSlashChars.ReplaceAllString(normalizedURL.Path, "/")
144 ctxlog.FromContext(r.Context()).Infof("escapedPath %s", normalizedURL.EscapedPath())
145 canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", r.Method, normalizedURL.EscapedPath(), s3querystring(r.URL), canonicalHeaders, signedHeaders, r.Header.Get("X-Amz-Content-Sha256"))
146 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
147 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
150 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
151 // scope is {datestamp}/{region}/{service}/aws4_request
152 drs := strings.Split(scope, "/")
154 return "", fmt.Errorf("invalid scope %q", scope)
156 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
157 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
160 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
162 func unescapeKey(key string) string {
163 if v2tokenUnderscore.MatchString(key) {
164 // Entire Arvados token, with "/" replaced by "_" to
165 // avoid colliding with the Authorization header
167 return strings.Replace(key, "_", "/", -1)
168 } else if s, err := url.PathUnescape(key); err == nil {
175 // checks3signature verifies the given S3 V4 signature and returns the
176 // Arvados token that corresponds to the given accessKey. An error is
177 // returned if accessKey is not a valid token UUID or the signature
179 func (h *handler) checks3signature(r *http.Request) (string, error) {
180 var key, scope, signedHeaders, signature string
181 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
182 for _, cmpt := range strings.Split(authstring, ",") {
183 cmpt = strings.TrimSpace(cmpt)
184 split := strings.SplitN(cmpt, "=", 2)
186 case len(split) != 2:
188 case split[0] == "Credential":
189 keyandscope := strings.SplitN(split[1], "/", 2)
190 if len(keyandscope) == 2 {
191 key, scope = keyandscope[0], keyandscope[1]
193 case split[0] == "SignedHeaders":
194 signedHeaders = split[1]
195 case split[0] == "Signature":
200 client := (&arvados.Client{
201 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
202 Insecure: h.Config.cluster.TLS.Insecure,
203 }).WithRequestID(r.Header.Get("X-Request-Id"))
204 var aca arvados.APIClientAuthorization
207 if len(key) == 27 && key[5:12] == "-gj3su-" {
208 // Access key is the UUID of an Arvados token, secret
209 // key is the secret part.
210 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
211 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
212 secret = aca.APIToken
214 // Access key and secret key are both an entire
215 // Arvados token or OIDC access token.
216 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
217 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
221 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
222 return "", errors.New("invalid access key")
224 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
228 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
231 } else if expect != signature {
232 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
234 return aca.TokenV2(), nil
237 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
238 w.Header().Set("Content-Type", "application/xml")
239 w.Header().Set("X-Content-Type-Options", "nosniff")
241 var errstruct struct {
247 errstruct.Code = s3code
248 errstruct.Message = message
249 errstruct.Resource = resource
250 errstruct.RequestId = ""
251 enc := xml.NewEncoder(w)
252 fmt.Fprint(w, xml.Header)
253 enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
256 var NoSuchKey = "NoSuchKey"
257 var NoSuchBucket = "NoSuchBucket"
258 var InvalidArgument = "InvalidArgument"
259 var InternalError = "InternalError"
260 var UnauthorizedAccess = "UnauthorizedAccess"
261 var InvalidRequest = "InvalidRequest"
262 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
264 var reRawQueryIndicatesAPI = regexp.MustCompile(`^[a-z]+(&|$)`)
266 // serveS3 handles r and returns true if r is a request from an S3
267 // client, otherwise it returns false.
268 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
270 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
271 split := strings.SplitN(auth[4:], ":", 2)
273 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
276 token = unescapeKey(split[0])
277 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
278 t, err := h.checks3signature(r)
280 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
289 var fs arvados.CustomFileSystem
290 var arvclient *arvadosclient.ArvadosClient
291 if r.Method == http.MethodGet || r.Method == http.MethodHead {
292 // Use a single session (cached FileSystem) across
293 // multiple read requests.
294 var sess *cachedSession
295 fs, sess, err = h.Config.Cache.GetSession(token)
297 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
300 arvclient = sess.arvadosclient
302 // Create a FileSystem for this request, to avoid
303 // exposing incomplete write operations to concurrent
305 var kc *keepclient.KeepClient
307 var client *arvados.Client
308 arvclient, kc, client, release, err = h.getClients(r.Header.Get("X-Request-Id"), token)
310 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
314 fs = client.SiteFileSystem(kc)
315 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
318 var objectNameGiven bool
319 var bucketName string
321 if id := parseCollectionIDFromDNSName(r.Host); id != "" {
324 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
326 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
327 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
329 fspath += reMultipleSlashChars.ReplaceAllString(r.URL.Path, "/")
332 case r.Method == http.MethodGet && !objectNameGiven:
333 // Path is "/{uuid}" or "/{uuid}/", has no object name
334 if _, ok := r.URL.Query()["versioning"]; ok {
335 // GetBucketVersioning
336 w.Header().Set("Content-Type", "application/xml")
337 io.WriteString(w, xml.Header)
338 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
339 } else if _, ok = r.URL.Query()["location"]; ok {
341 w.Header().Set("Content-Type", "application/xml")
342 io.WriteString(w, xml.Header)
343 fmt.Fprintln(w, `<LocationConstraint><LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`+
344 h.Config.cluster.ClusterID+
345 `</LocationConstraint></LocationConstraint>`)
346 } else if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
347 // GetBucketWebsite ("GET /bucketid/?website"), GetBucketTagging, etc.
348 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
351 h.s3list(bucketName, w, r, fs)
354 case r.Method == http.MethodGet || r.Method == http.MethodHead:
355 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
356 // GetObjectRetention ("GET /bucketid/objectid?retention&versionID=..."), etc.
357 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
360 fi, err := fs.Stat(fspath)
361 if r.Method == "HEAD" && !objectNameGiven {
363 if err == nil && fi.IsDir() {
364 w.WriteHeader(http.StatusOK)
365 } else if os.IsNotExist(err) {
366 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
368 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
372 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
373 w.Header().Set("Content-Type", "application/x-directory")
374 w.WriteHeader(http.StatusOK)
377 if os.IsNotExist(err) ||
378 (err != nil && err.Error() == "not a directory") ||
379 (fi != nil && fi.IsDir()) {
380 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
384 tokenUser, err := h.Config.Cache.GetTokenUser(token)
385 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
386 http.Error(w, "Not permitted", http.StatusForbidden)
389 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
391 // shallow copy r, and change URL path
394 http.FileServer(fs).ServeHTTP(w, &r)
396 case r.Method == http.MethodPut:
397 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
398 // PutObjectAcl ("PUT /bucketid/objectid?acl&versionID=..."), etc.
399 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
402 if !objectNameGiven {
403 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
407 if strings.HasSuffix(fspath, "/") {
408 if !h.Config.cluster.Collections.S3FolderObjects {
409 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
412 n, err := r.Body.Read(make([]byte, 1))
413 if err != nil && err != io.EOF {
414 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
417 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
419 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
420 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
423 // Given PUT "foo/bar/", we'll use "foo/bar/."
424 // in the "ensure parents exist" block below,
425 // and then we'll be done.
429 fi, err := fs.Stat(fspath)
430 if err != nil && err.Error() == "not a directory" {
431 // requested foo/bar, but foo is a file
432 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
435 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
436 // requested foo/bar/, but foo/bar is a file
437 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
440 // create missing parent/intermediate directories, if any
441 for i, c := range fspath {
442 if i > 0 && c == '/' {
444 if strings.HasSuffix(dir, "/") {
445 err = errors.New("invalid object name (consecutive '/' chars)")
446 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
449 err = fs.Mkdir(dir, 0755)
450 if err == arvados.ErrInvalidArgument {
451 // Cannot create a directory
453 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
454 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
456 } else if err != nil && !os.IsExist(err) {
457 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
458 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
464 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
465 if os.IsNotExist(err) {
466 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
469 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
470 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
475 tokenUser, err := h.Config.Cache.GetTokenUser(token)
476 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
477 http.Error(w, "Not permitted", http.StatusForbidden)
480 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
482 _, err = io.Copy(f, r.Body)
484 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
485 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
490 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
491 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
497 err = fmt.Errorf("sync failed: %w", err)
498 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
501 // Ensure a subsequent read operation will see the changes.
502 h.Config.Cache.ResetSession(token)
503 w.WriteHeader(http.StatusOK)
505 case r.Method == http.MethodDelete:
506 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
507 // DeleteObjectTagging ("DELETE /bucketid/objectid?tagging&versionID=..."), etc.
508 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
511 if !objectNameGiven || r.URL.Path == "/" {
512 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
515 if strings.HasSuffix(fspath, "/") {
516 fspath = strings.TrimSuffix(fspath, "/")
517 fi, err := fs.Stat(fspath)
518 if os.IsNotExist(err) {
519 w.WriteHeader(http.StatusNoContent)
521 } else if err != nil {
522 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
524 } else if !fi.IsDir() {
525 // if "foo" exists and is a file, then
526 // "foo/" doesn't exist, so we say
527 // delete was successful.
528 w.WriteHeader(http.StatusNoContent)
531 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
532 // if "foo" is a dir, it is visible via S3
533 // only as "foo/", not "foo" -- so we leave
534 // the dir alone and return 204 to indicate
535 // that "foo" does not exist.
536 w.WriteHeader(http.StatusNoContent)
539 err = fs.Remove(fspath)
540 if os.IsNotExist(err) {
541 w.WriteHeader(http.StatusNoContent)
545 err = fmt.Errorf("rm failed: %w", err)
546 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
551 err = fmt.Errorf("sync failed: %w", err)
552 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
555 // Ensure a subsequent read operation will see the changes.
556 h.Config.Cache.ResetSession(token)
557 w.WriteHeader(http.StatusNoContent)
560 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
565 // Call fn on the given path (directory) and its contents, in
566 // lexicographic order.
568 // If isRoot==true and path is not a directory, return nil.
570 // If fn returns filepath.SkipDir when called on a directory, don't
571 // descend into that directory.
572 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
574 fi, err := fs.Stat(path)
575 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
577 } else if err != nil {
581 if err == filepath.SkipDir {
583 } else if err != nil {
587 f, err := fs.Open(path)
588 if os.IsNotExist(err) && isRoot {
590 } else if err != nil {
591 return fmt.Errorf("open %q: %w", path, err)
597 fis, err := f.Readdir(-1)
601 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
602 for _, fi := range fis {
603 err = fn(path+"/"+fi.Name(), fi)
604 if err == filepath.SkipDir {
606 } else if err != nil {
610 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
619 var errDone = errors.New("done")
621 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
627 marker string // decoded continuationToken (v2) or provided by client (v1)
628 startAfter string // v2
629 continuationToken string // v2
630 encodingTypeURL bool // v2
632 params.delimiter = r.FormValue("delimiter")
633 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
634 params.maxKeys = int(mk)
636 params.maxKeys = s3MaxKeys
638 params.prefix = r.FormValue("prefix")
639 switch r.FormValue("list-type") {
644 http.Error(w, "invalid list-type parameter", http.StatusBadRequest)
648 params.continuationToken = r.FormValue("continuation-token")
649 marker, err := base64.StdEncoding.DecodeString(params.continuationToken)
651 http.Error(w, "invalid continuation token", http.StatusBadRequest)
654 params.marker = string(marker)
655 params.startAfter = r.FormValue("start-after")
656 switch r.FormValue("encoding-type") {
659 params.encodingTypeURL = true
661 http.Error(w, "invalid encoding-type parameter", http.StatusBadRequest)
665 params.marker = r.FormValue("marker")
668 bucketdir := "by_id/" + bucket
669 // walkpath is the directory (relative to bucketdir) we need
670 // to walk: the innermost directory that is guaranteed to
671 // contain all paths that have the requested prefix. Examples:
672 // prefix "foo/bar" => walkpath "foo"
673 // prefix "foo/bar/" => walkpath "foo/bar"
674 // prefix "foo" => walkpath ""
675 // prefix "" => walkpath ""
676 walkpath := params.prefix
677 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
678 walkpath = walkpath[:cut]
685 Prefix: params.prefix,
686 Delimiter: params.delimiter,
687 MaxKeys: params.maxKeys,
688 ContinuationToken: r.FormValue("continuation-token"),
689 StartAfter: params.startAfter,
693 commonPrefixes := map[string]bool{}
694 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
695 if path == bucketdir {
698 path = path[len(bucketdir)+1:]
699 filesize := fi.Size()
704 if len(path) <= len(params.prefix) {
705 if path > params.prefix[:len(path)] {
706 // with prefix "foobar", walking "fooz" means we're done
709 if path < params.prefix[:len(path)] {
710 // with prefix "foobar", walking "foobag" is pointless
711 return filepath.SkipDir
713 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
714 // with prefix "foo/bar", walking "fo"
715 // is pointless (but walking "foo" or
716 // "foo/bar" is necessary)
717 return filepath.SkipDir
719 if len(path) < len(params.prefix) {
720 // can't skip anything, and this entry
721 // isn't in the results, so just
726 if path[:len(params.prefix)] > params.prefix {
727 // with prefix "foobar", nothing we
728 // see after "foozzz" is relevant
732 if path < params.marker || path < params.prefix || path <= params.startAfter {
735 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
736 // Note we don't add anything to
737 // commonPrefixes here even if delimiter is
738 // "/". We descend into the directory, and
739 // return a commonPrefix only if we end up
740 // finding a regular file inside it.
743 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
744 resp.IsTruncated = true
745 if params.delimiter != "" || params.v2 {
750 if params.delimiter != "" {
751 idx := strings.Index(path[len(params.prefix):], params.delimiter)
753 // with prefix "foobar" and delimiter
754 // "z", when we hit "foobar/baz", we
755 // add "/baz" to commonPrefixes and
757 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
758 return filepath.SkipDir
761 resp.Contents = append(resp.Contents, s3.Key{
763 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
768 if err != nil && err != errDone {
769 http.Error(w, err.Error(), http.StatusInternalServerError)
772 if params.delimiter != "" {
773 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
774 for prefix := range commonPrefixes {
775 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
777 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
779 resp.KeyCount = len(resp.Contents)
780 var respV1orV2 interface{}
782 if params.encodingTypeURL {
783 // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
784 // "If you specify the encoding-type request
785 // parameter, Amazon S3 includes this element in the
786 // response, and returns encoded key name values in
787 // the following response elements:
789 // Delimiter, Prefix, Key, and StartAfter.
793 // Valid Values: url"
795 // This is somewhat vague but in practice it appears
796 // to mean x-www-form-urlencoded as in RFC1866 8.2.1
797 // para 1 (encode space as "+") rather than straight
798 // percent-encoding as in RFC1738 2.2. Presumably,
799 // the intent is to allow the client to decode XML and
800 // then paste the strings directly into another URI
801 // query or POST form like "https://host/path?foo=" +
802 // foo + "&bar=" + bar.
803 resp.EncodingType = "url"
804 resp.Delimiter = url.QueryEscape(resp.Delimiter)
805 resp.Prefix = url.QueryEscape(resp.Prefix)
806 resp.StartAfter = url.QueryEscape(resp.StartAfter)
807 for i, ent := range resp.Contents {
808 ent.Key = url.QueryEscape(ent.Key)
809 resp.Contents[i] = ent
811 for i, ent := range resp.CommonPrefixes {
812 ent.Prefix = url.QueryEscape(ent.Prefix)
813 resp.CommonPrefixes[i] = ent
818 resp.NextContinuationToken = base64.StdEncoding.EncodeToString([]byte(nextMarker))
821 respV1orV2 = listV1Resp{
822 CommonPrefixes: resp.CommonPrefixes,
823 NextMarker: nextMarker,
824 KeyCount: resp.KeyCount,
825 ListResp: s3.ListResp{
826 IsTruncated: resp.IsTruncated,
828 Prefix: params.prefix,
829 Delimiter: params.delimiter,
830 Marker: params.marker,
831 MaxKeys: params.maxKeys,
832 Contents: resp.Contents,
837 w.Header().Set("Content-Type", "application/xml")
838 io.WriteString(w, xml.Header)
839 if err := xml.NewEncoder(w).Encode(respV1orV2); err != nil {
840 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")