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 normalizedPath := normalizePath(r.URL.Path)
142 ctxlog.FromContext(r.Context()).Debugf("normalizedPath %q", normalizedPath)
143 canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", r.Method, normalizedPath, s3querystring(r.URL), canonicalHeaders, signedHeaders, r.Header.Get("X-Amz-Content-Sha256"))
144 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
145 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
148 func normalizePath(s string) string {
149 // (url.URL).EscapedPath() would be incorrect here. AWS
150 // documentation specifies the URL path should be normalized
151 // according to RFC 3986, i.e., unescaping ALPHA / DIGIT / "-"
152 // / "." / "_" / "~". The implication is that everything other
153 // than those chars (and "/") _must_ be percent-encoded --
154 // even chars like ";" and "," that are not normally
155 // percent-encoded in paths.
157 for _, c := range []byte(reMultipleSlashChars.ReplaceAllString(s, "/")) {
158 if (c >= 'a' && c <= 'z') ||
159 (c >= 'A' && c <= 'Z') ||
160 (c >= '0' && c <= '9') ||
168 out += fmt.Sprintf("%%%02X", c)
174 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
175 // scope is {datestamp}/{region}/{service}/aws4_request
176 drs := strings.Split(scope, "/")
178 return "", fmt.Errorf("invalid scope %q", scope)
180 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
181 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
184 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
186 func unescapeKey(key string) string {
187 if v2tokenUnderscore.MatchString(key) {
188 // Entire Arvados token, with "/" replaced by "_" to
189 // avoid colliding with the Authorization header
191 return strings.Replace(key, "_", "/", -1)
192 } else if s, err := url.PathUnescape(key); err == nil {
199 // checks3signature verifies the given S3 V4 signature and returns the
200 // Arvados token that corresponds to the given accessKey. An error is
201 // returned if accessKey is not a valid token UUID or the signature
203 func (h *handler) checks3signature(r *http.Request) (string, error) {
204 var key, scope, signedHeaders, signature string
205 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
206 for _, cmpt := range strings.Split(authstring, ",") {
207 cmpt = strings.TrimSpace(cmpt)
208 split := strings.SplitN(cmpt, "=", 2)
210 case len(split) != 2:
212 case split[0] == "Credential":
213 keyandscope := strings.SplitN(split[1], "/", 2)
214 if len(keyandscope) == 2 {
215 key, scope = keyandscope[0], keyandscope[1]
217 case split[0] == "SignedHeaders":
218 signedHeaders = split[1]
219 case split[0] == "Signature":
224 client := (&arvados.Client{
225 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
226 Insecure: h.Config.cluster.TLS.Insecure,
227 }).WithRequestID(r.Header.Get("X-Request-Id"))
228 var aca arvados.APIClientAuthorization
231 if len(key) == 27 && key[5:12] == "-gj3su-" {
232 // Access key is the UUID of an Arvados token, secret
233 // key is the secret part.
234 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
235 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
236 secret = aca.APIToken
238 // Access key and secret key are both an entire
239 // Arvados token or OIDC access token.
240 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
241 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
245 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
246 return "", errors.New("invalid access key")
248 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
252 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
255 } else if expect != signature {
256 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
258 return aca.TokenV2(), nil
261 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
262 w.Header().Set("Content-Type", "application/xml")
263 w.Header().Set("X-Content-Type-Options", "nosniff")
265 var errstruct struct {
271 errstruct.Code = s3code
272 errstruct.Message = message
273 errstruct.Resource = resource
274 errstruct.RequestId = ""
275 enc := xml.NewEncoder(w)
276 fmt.Fprint(w, xml.Header)
277 enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
280 var NoSuchKey = "NoSuchKey"
281 var NoSuchBucket = "NoSuchBucket"
282 var InvalidArgument = "InvalidArgument"
283 var InternalError = "InternalError"
284 var UnauthorizedAccess = "UnauthorizedAccess"
285 var InvalidRequest = "InvalidRequest"
286 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
288 var reRawQueryIndicatesAPI = regexp.MustCompile(`^[a-z]+(&|$)`)
290 // serveS3 handles r and returns true if r is a request from an S3
291 // client, otherwise it returns false.
292 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
294 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
295 split := strings.SplitN(auth[4:], ":", 2)
297 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
300 token = unescapeKey(split[0])
301 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
302 t, err := h.checks3signature(r)
304 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
313 var fs arvados.CustomFileSystem
314 var arvclient *arvadosclient.ArvadosClient
315 if r.Method == http.MethodGet || r.Method == http.MethodHead {
316 // Use a single session (cached FileSystem) across
317 // multiple read requests.
318 var sess *cachedSession
319 fs, sess, err = h.Config.Cache.GetSession(token)
321 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
324 arvclient = sess.arvadosclient
326 // Create a FileSystem for this request, to avoid
327 // exposing incomplete write operations to concurrent
329 var kc *keepclient.KeepClient
331 var client *arvados.Client
332 arvclient, kc, client, release, err = h.getClients(r.Header.Get("X-Request-Id"), token)
334 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
338 fs = client.SiteFileSystem(kc)
339 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
342 var objectNameGiven bool
343 var bucketName string
345 if id := parseCollectionIDFromDNSName(r.Host); id != "" {
348 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
350 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
351 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
353 fspath += reMultipleSlashChars.ReplaceAllString(r.URL.Path, "/")
356 case r.Method == http.MethodGet && !objectNameGiven:
357 // Path is "/{uuid}" or "/{uuid}/", has no object name
358 if _, ok := r.URL.Query()["versioning"]; ok {
359 // GetBucketVersioning
360 w.Header().Set("Content-Type", "application/xml")
361 io.WriteString(w, xml.Header)
362 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
363 } else if _, ok = r.URL.Query()["location"]; ok {
365 w.Header().Set("Content-Type", "application/xml")
366 io.WriteString(w, xml.Header)
367 fmt.Fprintln(w, `<LocationConstraint><LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`+
368 h.Config.cluster.ClusterID+
369 `</LocationConstraint></LocationConstraint>`)
370 } else if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
371 // GetBucketWebsite ("GET /bucketid/?website"), GetBucketTagging, etc.
372 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
375 h.s3list(bucketName, w, r, fs)
378 case r.Method == http.MethodGet || r.Method == http.MethodHead:
379 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
380 // GetObjectRetention ("GET /bucketid/objectid?retention&versionID=..."), etc.
381 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
384 fi, err := fs.Stat(fspath)
385 if r.Method == "HEAD" && !objectNameGiven {
387 if err == nil && fi.IsDir() {
388 w.WriteHeader(http.StatusOK)
389 } else if os.IsNotExist(err) {
390 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
392 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
396 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
397 w.Header().Set("Content-Type", "application/x-directory")
398 w.WriteHeader(http.StatusOK)
401 if os.IsNotExist(err) ||
402 (err != nil && err.Error() == "not a directory") ||
403 (fi != nil && fi.IsDir()) {
404 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
408 tokenUser, err := h.Config.Cache.GetTokenUser(token)
409 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
410 http.Error(w, "Not permitted", http.StatusForbidden)
413 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
415 // shallow copy r, and change URL path
418 http.FileServer(fs).ServeHTTP(w, &r)
420 case r.Method == http.MethodPut:
421 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
422 // PutObjectAcl ("PUT /bucketid/objectid?acl&versionID=..."), etc.
423 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
426 if !objectNameGiven {
427 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
431 if strings.HasSuffix(fspath, "/") {
432 if !h.Config.cluster.Collections.S3FolderObjects {
433 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
436 n, err := r.Body.Read(make([]byte, 1))
437 if err != nil && err != io.EOF {
438 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
441 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
443 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
444 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
447 // Given PUT "foo/bar/", we'll use "foo/bar/."
448 // in the "ensure parents exist" block below,
449 // and then we'll be done.
453 fi, err := fs.Stat(fspath)
454 if err != nil && err.Error() == "not a directory" {
455 // requested foo/bar, but foo is a file
456 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
459 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
460 // requested foo/bar/, but foo/bar is a file
461 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
464 // create missing parent/intermediate directories, if any
465 for i, c := range fspath {
466 if i > 0 && c == '/' {
468 if strings.HasSuffix(dir, "/") {
469 err = errors.New("invalid object name (consecutive '/' chars)")
470 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
473 err = fs.Mkdir(dir, 0755)
474 if err == arvados.ErrInvalidArgument {
475 // Cannot create a directory
477 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
478 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
480 } else if err != nil && !os.IsExist(err) {
481 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
482 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
488 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
489 if os.IsNotExist(err) {
490 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
493 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
494 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
499 tokenUser, err := h.Config.Cache.GetTokenUser(token)
500 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
501 http.Error(w, "Not permitted", http.StatusForbidden)
504 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
506 _, err = io.Copy(f, r.Body)
508 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
509 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
514 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
515 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
521 err = fmt.Errorf("sync failed: %w", err)
522 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
525 // Ensure a subsequent read operation will see the changes.
526 h.Config.Cache.ResetSession(token)
527 w.WriteHeader(http.StatusOK)
529 case r.Method == http.MethodDelete:
530 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
531 // DeleteObjectTagging ("DELETE /bucketid/objectid?tagging&versionID=..."), etc.
532 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
535 if !objectNameGiven || r.URL.Path == "/" {
536 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
539 if strings.HasSuffix(fspath, "/") {
540 fspath = strings.TrimSuffix(fspath, "/")
541 fi, err := fs.Stat(fspath)
542 if os.IsNotExist(err) {
543 w.WriteHeader(http.StatusNoContent)
545 } else if err != nil {
546 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
548 } else if !fi.IsDir() {
549 // if "foo" exists and is a file, then
550 // "foo/" doesn't exist, so we say
551 // delete was successful.
552 w.WriteHeader(http.StatusNoContent)
555 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
556 // if "foo" is a dir, it is visible via S3
557 // only as "foo/", not "foo" -- so we leave
558 // the dir alone and return 204 to indicate
559 // that "foo" does not exist.
560 w.WriteHeader(http.StatusNoContent)
563 err = fs.Remove(fspath)
564 if os.IsNotExist(err) {
565 w.WriteHeader(http.StatusNoContent)
569 err = fmt.Errorf("rm failed: %w", err)
570 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
575 err = fmt.Errorf("sync failed: %w", err)
576 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
579 // Ensure a subsequent read operation will see the changes.
580 h.Config.Cache.ResetSession(token)
581 w.WriteHeader(http.StatusNoContent)
584 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
589 // Call fn on the given path (directory) and its contents, in
590 // lexicographic order.
592 // If isRoot==true and path is not a directory, return nil.
594 // If fn returns filepath.SkipDir when called on a directory, don't
595 // descend into that directory.
596 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
598 fi, err := fs.Stat(path)
599 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
601 } else if err != nil {
605 if err == filepath.SkipDir {
607 } else if err != nil {
611 f, err := fs.Open(path)
612 if os.IsNotExist(err) && isRoot {
614 } else if err != nil {
615 return fmt.Errorf("open %q: %w", path, err)
621 fis, err := f.Readdir(-1)
625 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
626 for _, fi := range fis {
627 err = fn(path+"/"+fi.Name(), fi)
628 if err == filepath.SkipDir {
630 } else if err != nil {
634 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
643 var errDone = errors.New("done")
645 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
651 marker string // decoded continuationToken (v2) or provided by client (v1)
652 startAfter string // v2
653 continuationToken string // v2
654 encodingTypeURL bool // v2
656 params.delimiter = r.FormValue("delimiter")
657 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
658 params.maxKeys = int(mk)
660 params.maxKeys = s3MaxKeys
662 params.prefix = r.FormValue("prefix")
663 switch r.FormValue("list-type") {
668 http.Error(w, "invalid list-type parameter", http.StatusBadRequest)
672 params.continuationToken = r.FormValue("continuation-token")
673 marker, err := base64.StdEncoding.DecodeString(params.continuationToken)
675 http.Error(w, "invalid continuation token", http.StatusBadRequest)
678 params.marker = string(marker)
679 params.startAfter = r.FormValue("start-after")
680 switch r.FormValue("encoding-type") {
683 params.encodingTypeURL = true
685 http.Error(w, "invalid encoding-type parameter", http.StatusBadRequest)
689 params.marker = r.FormValue("marker")
692 bucketdir := "by_id/" + bucket
693 // walkpath is the directory (relative to bucketdir) we need
694 // to walk: the innermost directory that is guaranteed to
695 // contain all paths that have the requested prefix. Examples:
696 // prefix "foo/bar" => walkpath "foo"
697 // prefix "foo/bar/" => walkpath "foo/bar"
698 // prefix "foo" => walkpath ""
699 // prefix "" => walkpath ""
700 walkpath := params.prefix
701 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
702 walkpath = walkpath[:cut]
709 Prefix: params.prefix,
710 Delimiter: params.delimiter,
711 MaxKeys: params.maxKeys,
712 ContinuationToken: r.FormValue("continuation-token"),
713 StartAfter: params.startAfter,
717 commonPrefixes := map[string]bool{}
718 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
719 if path == bucketdir {
722 path = path[len(bucketdir)+1:]
723 filesize := fi.Size()
728 if len(path) <= len(params.prefix) {
729 if path > params.prefix[:len(path)] {
730 // with prefix "foobar", walking "fooz" means we're done
733 if path < params.prefix[:len(path)] {
734 // with prefix "foobar", walking "foobag" is pointless
735 return filepath.SkipDir
737 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
738 // with prefix "foo/bar", walking "fo"
739 // is pointless (but walking "foo" or
740 // "foo/bar" is necessary)
741 return filepath.SkipDir
743 if len(path) < len(params.prefix) {
744 // can't skip anything, and this entry
745 // isn't in the results, so just
750 if path[:len(params.prefix)] > params.prefix {
751 // with prefix "foobar", nothing we
752 // see after "foozzz" is relevant
756 if path < params.marker || path < params.prefix || path <= params.startAfter {
759 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
760 // Note we don't add anything to
761 // commonPrefixes here even if delimiter is
762 // "/". We descend into the directory, and
763 // return a commonPrefix only if we end up
764 // finding a regular file inside it.
767 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
768 resp.IsTruncated = true
769 if params.delimiter != "" || params.v2 {
774 if params.delimiter != "" {
775 idx := strings.Index(path[len(params.prefix):], params.delimiter)
777 // with prefix "foobar" and delimiter
778 // "z", when we hit "foobar/baz", we
779 // add "/baz" to commonPrefixes and
781 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
782 return filepath.SkipDir
785 resp.Contents = append(resp.Contents, s3.Key{
787 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
792 if err != nil && err != errDone {
793 http.Error(w, err.Error(), http.StatusInternalServerError)
796 if params.delimiter != "" {
797 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
798 for prefix := range commonPrefixes {
799 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
801 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
803 resp.KeyCount = len(resp.Contents)
804 var respV1orV2 interface{}
806 if params.encodingTypeURL {
807 // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
808 // "If you specify the encoding-type request
809 // parameter, Amazon S3 includes this element in the
810 // response, and returns encoded key name values in
811 // the following response elements:
813 // Delimiter, Prefix, Key, and StartAfter.
817 // Valid Values: url"
819 // This is somewhat vague but in practice it appears
820 // to mean x-www-form-urlencoded as in RFC1866 8.2.1
821 // para 1 (encode space as "+") rather than straight
822 // percent-encoding as in RFC1738 2.2. Presumably,
823 // the intent is to allow the client to decode XML and
824 // then paste the strings directly into another URI
825 // query or POST form like "https://host/path?foo=" +
826 // foo + "&bar=" + bar.
827 resp.EncodingType = "url"
828 resp.Delimiter = url.QueryEscape(resp.Delimiter)
829 resp.Prefix = url.QueryEscape(resp.Prefix)
830 resp.StartAfter = url.QueryEscape(resp.StartAfter)
831 for i, ent := range resp.Contents {
832 ent.Key = url.QueryEscape(ent.Key)
833 resp.Contents[i] = ent
835 for i, ent := range resp.CommonPrefixes {
836 ent.Prefix = url.QueryEscape(ent.Prefix)
837 resp.CommonPrefixes[i] = ent
842 resp.NextContinuationToken = base64.StdEncoding.EncodeToString([]byte(nextMarker))
845 respV1orV2 = listV1Resp{
846 CommonPrefixes: resp.CommonPrefixes,
847 NextMarker: nextMarker,
848 KeyCount: resp.KeyCount,
849 ListResp: s3.ListResp{
850 IsTruncated: resp.IsTruncated,
852 Prefix: params.prefix,
853 Delimiter: params.delimiter,
854 Marker: params.marker,
855 MaxKeys: params.maxKeys,
856 Contents: resp.Contents,
861 w.Header().Set("Content-Type", "application/xml")
862 io.WriteString(w, xml.Header)
863 if err := xml.NewEncoder(w).Encode(respV1orV2); err != nil {
864 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")