1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.arvados.org/arvados.git/sdk/go/arvados"
20 "git.arvados.org/arvados.git/sdk/go/ctxlog"
21 "github.com/AdRoll/goamz/s3"
24 const s3MaxKeys = 1000
26 // serveS3 handles r and returns true if r is a request from an S3
27 // client, otherwise it returns false.
28 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
30 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
31 split := strings.SplitN(auth[4:], ":", 2)
33 w.WriteHeader(http.StatusUnauthorized)
37 } else if strings.HasPrefix(auth, "AWS4-HMAC-SHA256 ") {
38 for _, cmpt := range strings.Split(auth[17:], ",") {
39 cmpt = strings.TrimSpace(cmpt)
40 split := strings.SplitN(cmpt, "=", 2)
41 if len(split) == 2 && split[0] == "Credential" {
42 keyandscope := strings.Split(split[1], "/")
43 if len(keyandscope[0]) > 0 {
44 token = keyandscope[0]
50 w.WriteHeader(http.StatusBadRequest)
51 fmt.Println(w, "invalid V4 signature")
58 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
60 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
65 fs := client.SiteFileSystem(kc)
66 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
68 objectNameGiven := strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
71 case r.Method == http.MethodGet && !objectNameGiven:
72 // Path is "/{uuid}" or "/{uuid}/", has no object name
73 if _, ok := r.URL.Query()["versioning"]; ok {
74 // GetBucketVersioning
75 w.Header().Set("Content-Type", "application/xml")
76 io.WriteString(w, xml.Header)
77 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
83 case r.Method == http.MethodGet || r.Method == http.MethodHead:
84 fspath := "/by_id" + r.URL.Path
85 fi, err := fs.Stat(fspath)
86 if r.Method == "HEAD" && !objectNameGiven {
88 if err == nil && fi.IsDir() {
89 w.WriteHeader(http.StatusOK)
90 } else if os.IsNotExist(err) {
91 w.WriteHeader(http.StatusNotFound)
93 http.Error(w, err.Error(), http.StatusBadGateway)
97 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
98 w.Header().Set("Content-Type", "application/x-directory")
99 w.WriteHeader(http.StatusOK)
102 if os.IsNotExist(err) ||
103 (err != nil && err.Error() == "not a directory") ||
104 (fi != nil && fi.IsDir()) {
105 http.Error(w, "not found", http.StatusNotFound)
108 // shallow copy r, and change URL path
111 http.FileServer(fs).ServeHTTP(w, &r)
113 case r.Method == http.MethodPut:
114 if !objectNameGiven {
115 http.Error(w, "missing object name in PUT request", http.StatusBadRequest)
118 fspath := "by_id" + r.URL.Path
120 if strings.HasSuffix(fspath, "/") {
121 if !h.Config.cluster.Collections.S3FolderObjects {
122 http.Error(w, "invalid object name: trailing slash", http.StatusBadRequest)
125 n, err := r.Body.Read(make([]byte, 1))
126 if err != nil && err != io.EOF {
127 http.Error(w, fmt.Sprintf("error reading request body: %s", err), http.StatusInternalServerError)
130 http.Error(w, "cannot create object with trailing '/' char unless content is empty", http.StatusBadRequest)
132 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
133 http.Error(w, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", http.StatusBadRequest)
136 // Given PUT "foo/bar/", we'll use "foo/bar/."
137 // in the "ensure parents exist" block below,
138 // and then we'll be done.
142 fi, err := fs.Stat(fspath)
143 if err != nil && err.Error() == "not a directory" {
144 // requested foo/bar, but foo is a file
145 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
148 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
149 // requested foo/bar/, but foo/bar is a file
150 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
153 // create missing parent/intermediate directories, if any
154 for i, c := range fspath {
155 if i > 0 && c == '/' {
157 if strings.HasSuffix(dir, "/") {
158 err = errors.New("invalid object name (consecutive '/' chars)")
159 http.Error(w, err.Error(), http.StatusBadRequest)
162 err = fs.Mkdir(dir, 0755)
163 if err == arvados.ErrInvalidArgument {
164 // Cannot create a directory
166 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
167 http.Error(w, err.Error(), http.StatusBadRequest)
169 } else if err != nil && !os.IsExist(err) {
170 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
171 http.Error(w, err.Error(), http.StatusInternalServerError)
177 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
178 if os.IsNotExist(err) {
179 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
182 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
183 http.Error(w, err.Error(), http.StatusBadRequest)
187 _, err = io.Copy(f, r.Body)
189 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
190 http.Error(w, err.Error(), http.StatusBadGateway)
195 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
196 http.Error(w, err.Error(), http.StatusBadGateway)
202 err = fmt.Errorf("sync failed: %w", err)
203 http.Error(w, err.Error(), http.StatusInternalServerError)
206 w.WriteHeader(http.StatusOK)
209 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
214 // Call fn on the given path (directory) and its contents, in
215 // lexicographic order.
217 // If isRoot==true and path is not a directory, return nil.
219 // If fn returns filepath.SkipDir when called on a directory, don't
220 // descend into that directory.
221 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
223 fi, err := fs.Stat(path)
224 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
226 } else if err != nil {
230 if err == filepath.SkipDir {
232 } else if err != nil {
236 f, err := fs.Open(path)
237 if os.IsNotExist(err) && isRoot {
239 } else if err != nil {
240 return fmt.Errorf("open %q: %w", path, err)
246 fis, err := f.Readdir(-1)
250 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
251 for _, fi := range fis {
252 err = fn(path+"/"+fi.Name(), fi)
253 if err == filepath.SkipDir {
255 } else if err != nil {
259 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
268 var errDone = errors.New("done")
270 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
278 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
279 params.delimiter = r.FormValue("delimiter")
280 params.marker = r.FormValue("marker")
281 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
282 params.maxKeys = int(mk)
284 params.maxKeys = s3MaxKeys
286 params.prefix = r.FormValue("prefix")
288 bucketdir := "by_id/" + params.bucket
289 // walkpath is the directory (relative to bucketdir) we need
290 // to walk: the innermost directory that is guaranteed to
291 // contain all paths that have the requested prefix. Examples:
292 // prefix "foo/bar" => walkpath "foo"
293 // prefix "foo/bar/" => walkpath "foo/bar"
294 // prefix "foo" => walkpath ""
295 // prefix "" => walkpath ""
296 walkpath := params.prefix
297 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
298 walkpath = walkpath[:cut]
304 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
305 Prefix: params.prefix,
306 Delimiter: params.delimiter,
307 Marker: params.marker,
308 MaxKeys: params.maxKeys,
310 commonPrefixes := map[string]bool{}
311 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
312 if path == bucketdir {
315 path = path[len(bucketdir)+1:]
316 filesize := fi.Size()
321 if len(path) <= len(params.prefix) {
322 if path > params.prefix[:len(path)] {
323 // with prefix "foobar", walking "fooz" means we're done
326 if path < params.prefix[:len(path)] {
327 // with prefix "foobar", walking "foobag" is pointless
328 return filepath.SkipDir
330 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
331 // with prefix "foo/bar", walking "fo"
332 // is pointless (but walking "foo" or
333 // "foo/bar" is necessary)
334 return filepath.SkipDir
336 if len(path) < len(params.prefix) {
337 // can't skip anything, and this entry
338 // isn't in the results, so just
343 if path[:len(params.prefix)] > params.prefix {
344 // with prefix "foobar", nothing we
345 // see after "foozzz" is relevant
349 if path < params.marker || path < params.prefix {
352 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
353 // Note we don't add anything to
354 // commonPrefixes here even if delimiter is
355 // "/". We descend into the directory, and
356 // return a commonPrefix only if we end up
357 // finding a regular file inside it.
360 if params.delimiter != "" {
361 idx := strings.Index(path[len(params.prefix):], params.delimiter)
363 // with prefix "foobar" and delimiter
364 // "z", when we hit "foobar/baz", we
365 // add "/baz" to commonPrefixes and
367 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
368 return filepath.SkipDir
371 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
372 resp.IsTruncated = true
373 if params.delimiter != "" {
374 resp.NextMarker = path
378 resp.Contents = append(resp.Contents, s3.Key{
380 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
385 if err != nil && err != errDone {
386 http.Error(w, err.Error(), http.StatusInternalServerError)
389 if params.delimiter != "" {
390 for prefix := range commonPrefixes {
391 resp.CommonPrefixes = append(resp.CommonPrefixes, prefix)
392 sort.Strings(resp.CommonPrefixes)
395 wrappedResp := struct {
396 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
399 w.Header().Set("Content-Type", "application/xml")
400 io.WriteString(w, xml.Header)
401 if err := xml.NewEncoder(w).Encode(wrappedResp); err != nil {
402 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")