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 == "GET" && !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 == "GET" || r.Method == "HEAD":
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 os.IsNotExist(err) ||
98 (err != nil && err.Error() == "not a directory") ||
99 (fi != nil && fi.IsDir()) {
100 http.Error(w, "not found", http.StatusNotFound)
103 // shallow copy r, and change URL path
106 http.FileServer(fs).ServeHTTP(w, &r)
108 case r.Method == "PUT":
109 if strings.HasSuffix(r.URL.Path, "/") {
110 http.Error(w, "invalid object name (trailing '/' char)", http.StatusBadRequest)
113 fspath := "by_id" + r.URL.Path
114 _, err = fs.Stat(fspath)
115 if err != nil && err.Error() == "not a directory" {
116 // requested foo/bar, but foo is a file
117 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
120 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
121 if os.IsNotExist(err) {
122 // create missing intermediate directories, then try again
123 for i, c := range fspath {
124 if i > 0 && c == '/' {
126 if strings.HasSuffix(dir, "/") {
127 err = errors.New("invalid object name (consecutive '/' chars)")
128 http.Error(w, err.Error(), http.StatusBadRequest)
131 err := fs.Mkdir(dir, 0755)
132 if err != nil && err != os.ErrExist {
133 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
134 http.Error(w, err.Error(), http.StatusInternalServerError)
139 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
142 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
143 http.Error(w, err.Error(), http.StatusBadRequest)
147 _, err = io.Copy(f, r.Body)
149 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
150 http.Error(w, err.Error(), http.StatusBadGateway)
155 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
156 http.Error(w, err.Error(), http.StatusBadGateway)
161 err = fmt.Errorf("sync failed: %w", err)
162 http.Error(w, err.Error(), http.StatusInternalServerError)
165 w.WriteHeader(http.StatusOK)
168 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
173 func walkFS(fs arvados.CustomFileSystem, path string, ignoreNotFound bool, fn func(path string, fi os.FileInfo) error) error {
174 f, err := fs.Open(path)
175 if os.IsNotExist(err) && ignoreNotFound {
177 } else if err != nil {
178 return fmt.Errorf("open %q: %w", path, err)
184 fis, err := f.Readdir(-1)
188 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
189 for _, fi := range fis {
190 err = fn(path+"/"+fi.Name(), fi)
191 if err == filepath.SkipDir {
193 } else if err != nil {
197 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
206 var errDone = errors.New("done")
208 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
216 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
217 params.delimiter = r.FormValue("delimiter")
218 params.marker = r.FormValue("marker")
219 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
220 params.maxKeys = int(mk)
222 params.maxKeys = s3MaxKeys
224 params.prefix = r.FormValue("prefix")
226 bucketdir := "by_id/" + params.bucket
227 // walkpath is the directory (relative to bucketdir) we need
228 // to walk: the innermost directory that is guaranteed to
229 // contain all paths that have the requested prefix. Examples:
230 // prefix "foo/bar" => walkpath "foo"
231 // prefix "foo/bar/" => walkpath "foo/bar"
232 // prefix "foo" => walkpath ""
233 // prefix "" => walkpath ""
234 walkpath := params.prefix
235 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
236 walkpath = walkpath[:cut]
242 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
243 Prefix: params.prefix,
244 Delimiter: params.delimiter,
245 Marker: params.marker,
246 MaxKeys: params.maxKeys,
248 commonPrefixes := map[string]bool{}
249 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
250 path = path[len(bucketdir)+1:]
251 if len(path) <= len(params.prefix) {
252 if path > params.prefix[:len(path)] {
253 // with prefix "foobar", walking "fooz" means we're done
256 if path < params.prefix[:len(path)] {
257 // with prefix "foobar", walking "foobag" is pointless
258 return filepath.SkipDir
260 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path+"/") {
261 // with prefix "foo/bar", walking "fo"
262 // is pointless (but walking "foo" or
263 // "foo/bar" is necessary)
264 return filepath.SkipDir
266 if len(path) < len(params.prefix) {
267 // can't skip anything, and this entry
268 // isn't in the results, so just
273 if path[:len(params.prefix)] > params.prefix {
274 // with prefix "foobar", nothing we
275 // see after "foozzz" is relevant
279 if path < params.marker || path < params.prefix {
285 if params.delimiter != "" {
286 idx := strings.Index(path[len(params.prefix):], params.delimiter)
288 // with prefix "foobar" and delimiter
289 // "z", when we hit "foobar/baz", we
290 // add "/baz" to commonPrefixes and
291 // stop descending (note that even if
292 // delimiter is "/" we don't add
293 // anything to commonPrefixes when
294 // seeing a dir: we wait until we see
295 // a file, so we don't incorrectly
296 // return results for empty dirs)
297 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
298 return filepath.SkipDir
301 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
302 resp.IsTruncated = true
303 if params.delimiter != "" {
304 resp.NextMarker = path
308 resp.Contents = append(resp.Contents, s3.Key{
313 if err != nil && err != errDone {
314 http.Error(w, err.Error(), http.StatusInternalServerError)
317 if params.delimiter != "" {
318 for prefix := range commonPrefixes {
319 resp.CommonPrefixes = append(resp.CommonPrefixes, prefix)
320 sort.Strings(resp.CommonPrefixes)
323 wrappedResp := struct {
324 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
327 w.Header().Set("Content-Type", "application/xml")
328 io.WriteString(w, xml.Header)
329 if err := xml.NewEncoder(w).Encode(wrappedResp); err != nil {
330 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")