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 "git.arvados.org/arvados.git/tmp/GOPATH/src/github.com/AdRoll/goamz/s3"
24 // serveS3 handles r and returns true if r is a request from an S3
25 // client, otherwise it returns false.
26 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
28 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
29 split := strings.SplitN(auth[4:], ":", 2)
31 w.WriteHeader(http.StatusUnauthorized)
35 } else if strings.HasPrefix(auth, "AWS4-HMAC-SHA256 ") {
36 w.WriteHeader(http.StatusBadRequest)
37 fmt.Println(w, "V4 signature is not supported")
43 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
45 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
50 fs := client.SiteFileSystem(kc)
51 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
54 case r.Method == "GET" && strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") == 1:
55 // Path is "/{uuid}" or "/{uuid}/", has no object name
58 case r.Method == "GET":
59 fspath := "/by_id" + r.URL.Path
60 fi, err := fs.Stat(fspath)
61 if os.IsNotExist(err) ||
62 (err != nil && err.Error() == "not a directory") ||
63 (fi != nil && fi.IsDir()) {
64 http.Error(w, "not found", http.StatusNotFound)
67 // shallow copy r, and change URL path
70 http.FileServer(fs).ServeHTTP(w, &r)
72 case r.Method == "PUT":
73 if strings.HasSuffix(r.URL.Path, "/") {
74 http.Error(w, "invalid object name (trailing '/' char)", http.StatusBadRequest)
77 fspath := "by_id" + r.URL.Path
78 _, err = fs.Stat(fspath)
79 if err != nil && err.Error() == "not a directory" {
80 // requested foo/bar, but foo is a file
81 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
84 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
85 if os.IsNotExist(err) {
86 // create missing intermediate directories, then try again
87 for i, c := range fspath {
88 if i > 0 && c == '/' {
90 if strings.HasSuffix(dir, "/") {
91 err = errors.New("invalid object name (consecutive '/' chars)")
92 http.Error(w, err.Error(), http.StatusBadRequest)
95 err := fs.Mkdir(dir, 0755)
96 if err != nil && err != os.ErrExist {
97 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
98 http.Error(w, err.Error(), http.StatusInternalServerError)
103 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
106 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
107 http.Error(w, err.Error(), http.StatusBadRequest)
111 _, err = io.Copy(f, r.Body)
113 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
114 http.Error(w, err.Error(), http.StatusBadGateway)
119 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
120 http.Error(w, err.Error(), http.StatusBadGateway)
125 err = fmt.Errorf("sync failed: %w", err)
126 http.Error(w, err.Error(), http.StatusInternalServerError)
129 w.WriteHeader(http.StatusOK)
132 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
137 func walkFS(fs arvados.CustomFileSystem, path string, ignoreNotFound bool, fn func(path string, fi os.FileInfo) error) error {
138 f, err := fs.Open(path)
139 if os.IsNotExist(err) && ignoreNotFound {
141 } else if err != nil {
142 return fmt.Errorf("open %q: %w", path, err)
148 fis, err := f.Readdir(-1)
152 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
153 for _, fi := range fis {
154 err = fn(path+"/"+fi.Name(), fi)
155 if err == filepath.SkipDir {
157 } else if err != nil {
161 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
170 var errDone = errors.New("done")
172 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
180 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
181 params.delimiter = r.FormValue("delimiter")
182 params.marker = r.FormValue("marker")
183 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 {
184 params.maxKeys = int(mk)
188 params.prefix = r.FormValue("prefix")
190 bucketdir := "by_id/" + params.bucket
191 // walkpath is the directory (relative to bucketdir) we need
192 // to walk: the innermost directory that is guaranteed to
193 // contain all paths that have the requested prefix. Examples:
194 // prefix "foo/bar" => walkpath "foo"
195 // prefix "foo/bar/" => walkpath "foo/bar"
196 // prefix "foo" => walkpath ""
197 // prefix "" => walkpath ""
198 walkpath := params.prefix
199 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
200 walkpath = walkpath[:cut]
206 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
207 Prefix: params.prefix,
208 Delimiter: params.delimiter,
209 Marker: params.marker,
210 MaxKeys: params.maxKeys,
212 commonPrefixes := map[string]bool{}
213 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
214 path = path[len(bucketdir)+1:]
215 if len(path) <= len(params.prefix) {
216 if path > params.prefix[:len(path)] {
217 // with prefix "foobar", walking "fooz" means we're done
220 if path < params.prefix[:len(path)] {
221 // with prefix "foobar", walking "foobag" is pointless
222 return filepath.SkipDir
224 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path+"/") {
225 // with prefix "foo/bar", walking "fo"
226 // is pointless (but walking "foo" or
227 // "foo/bar" is necessary)
228 return filepath.SkipDir
230 if len(path) < len(params.prefix) {
231 // can't skip anything, and this entry
232 // isn't in the results, so just
237 if path[:len(params.prefix)] > params.prefix {
238 // with prefix "foobar", nothing we
239 // see after "foozzz" is relevant
243 if path < params.marker || path < params.prefix {
249 if params.delimiter != "" {
250 idx := strings.Index(path[len(params.prefix):], params.delimiter)
252 // with prefix "foobar" and delimiter
253 // "z", when we hit "foobar/baz", we
254 // add "/baz" to commonPrefixes and
255 // stop descending (note that even if
256 // delimiter is "/" we don't add
257 // anything to commonPrefixes when
258 // seeing a dir: we wait until we see
259 // a file, so we don't incorrectly
260 // return results for empty dirs)
261 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
262 return filepath.SkipDir
265 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
266 resp.IsTruncated = true
267 if params.delimiter != "" {
268 resp.NextMarker = path
272 resp.Contents = append(resp.Contents, s3.Key{
277 if err != nil && err != errDone {
278 http.Error(w, err.Error(), http.StatusInternalServerError)
281 if params.delimiter != "" {
282 for prefix := range commonPrefixes {
283 resp.CommonPrefixes = append(resp.CommonPrefixes, prefix)
284 sort.Strings(resp.CommonPrefixes)
287 if err := xml.NewEncoder(w).Encode(resp); err != nil {
288 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")