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)
69 case r.Method == "GET" && strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") == 1:
70 // Path is "/{uuid}" or "/{uuid}/", has no object name
73 case r.Method == "GET":
74 fspath := "/by_id" + r.URL.Path
75 fi, err := fs.Stat(fspath)
76 if os.IsNotExist(err) ||
77 (err != nil && err.Error() == "not a directory") ||
78 (fi != nil && fi.IsDir()) {
79 http.Error(w, "not found", http.StatusNotFound)
82 // shallow copy r, and change URL path
85 http.FileServer(fs).ServeHTTP(w, &r)
87 case r.Method == "PUT":
88 if strings.HasSuffix(r.URL.Path, "/") {
89 http.Error(w, "invalid object name (trailing '/' char)", http.StatusBadRequest)
92 fspath := "by_id" + r.URL.Path
93 _, err = fs.Stat(fspath)
94 if err != nil && err.Error() == "not a directory" {
95 // requested foo/bar, but foo is a file
96 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
99 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
100 if os.IsNotExist(err) {
101 // create missing intermediate directories, then try again
102 for i, c := range fspath {
103 if i > 0 && c == '/' {
105 if strings.HasSuffix(dir, "/") {
106 err = errors.New("invalid object name (consecutive '/' chars)")
107 http.Error(w, err.Error(), http.StatusBadRequest)
110 err := fs.Mkdir(dir, 0755)
111 if err != nil && err != os.ErrExist {
112 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
113 http.Error(w, err.Error(), http.StatusInternalServerError)
118 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
121 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
122 http.Error(w, err.Error(), http.StatusBadRequest)
126 _, err = io.Copy(f, r.Body)
128 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
129 http.Error(w, err.Error(), http.StatusBadGateway)
134 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
135 http.Error(w, err.Error(), http.StatusBadGateway)
140 err = fmt.Errorf("sync failed: %w", err)
141 http.Error(w, err.Error(), http.StatusInternalServerError)
144 w.WriteHeader(http.StatusOK)
147 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
152 func walkFS(fs arvados.CustomFileSystem, path string, ignoreNotFound bool, fn func(path string, fi os.FileInfo) error) error {
153 f, err := fs.Open(path)
154 if os.IsNotExist(err) && ignoreNotFound {
156 } else if err != nil {
157 return fmt.Errorf("open %q: %w", path, err)
163 fis, err := f.Readdir(-1)
167 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
168 for _, fi := range fis {
169 err = fn(path+"/"+fi.Name(), fi)
170 if err == filepath.SkipDir {
172 } else if err != nil {
176 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
185 var errDone = errors.New("done")
187 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
195 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
196 params.delimiter = r.FormValue("delimiter")
197 params.marker = r.FormValue("marker")
198 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
199 params.maxKeys = int(mk)
201 params.maxKeys = s3MaxKeys
203 params.prefix = r.FormValue("prefix")
205 bucketdir := "by_id/" + params.bucket
206 // walkpath is the directory (relative to bucketdir) we need
207 // to walk: the innermost directory that is guaranteed to
208 // contain all paths that have the requested prefix. Examples:
209 // prefix "foo/bar" => walkpath "foo"
210 // prefix "foo/bar/" => walkpath "foo/bar"
211 // prefix "foo" => walkpath ""
212 // prefix "" => walkpath ""
213 walkpath := params.prefix
214 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
215 walkpath = walkpath[:cut]
221 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
222 Prefix: params.prefix,
223 Delimiter: params.delimiter,
224 Marker: params.marker,
225 MaxKeys: params.maxKeys,
227 commonPrefixes := map[string]bool{}
228 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
229 path = path[len(bucketdir)+1:]
230 if len(path) <= len(params.prefix) {
231 if path > params.prefix[:len(path)] {
232 // with prefix "foobar", walking "fooz" means we're done
235 if path < params.prefix[:len(path)] {
236 // with prefix "foobar", walking "foobag" is pointless
237 return filepath.SkipDir
239 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path+"/") {
240 // with prefix "foo/bar", walking "fo"
241 // is pointless (but walking "foo" or
242 // "foo/bar" is necessary)
243 return filepath.SkipDir
245 if len(path) < len(params.prefix) {
246 // can't skip anything, and this entry
247 // isn't in the results, so just
252 if path[:len(params.prefix)] > params.prefix {
253 // with prefix "foobar", nothing we
254 // see after "foozzz" is relevant
258 if path < params.marker || path < params.prefix {
264 if params.delimiter != "" {
265 idx := strings.Index(path[len(params.prefix):], params.delimiter)
267 // with prefix "foobar" and delimiter
268 // "z", when we hit "foobar/baz", we
269 // add "/baz" to commonPrefixes and
270 // stop descending (note that even if
271 // delimiter is "/" we don't add
272 // anything to commonPrefixes when
273 // seeing a dir: we wait until we see
274 // a file, so we don't incorrectly
275 // return results for empty dirs)
276 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
277 return filepath.SkipDir
280 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
281 resp.IsTruncated = true
282 if params.delimiter != "" {
283 resp.NextMarker = path
287 resp.Contents = append(resp.Contents, s3.Key{
292 if err != nil && err != errDone {
293 http.Error(w, err.Error(), http.StatusInternalServerError)
296 if params.delimiter != "" {
297 for prefix := range commonPrefixes {
298 resp.CommonPrefixes = append(resp.CommonPrefixes, prefix)
299 sort.Strings(resp.CommonPrefixes)
302 if err := xml.NewEncoder(w).Encode(resp); err != nil {
303 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")