s3api_object_handlers.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package s3api
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/seaweedfs/seaweedfs/weed/filer"
  6. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  13. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  14. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  15. "github.com/seaweedfs/seaweedfs/weed/glog"
  16. util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
  17. )
  18. func mimeDetect(r *http.Request, dataReader io.Reader) io.ReadCloser {
  19. mimeBuffer := make([]byte, 512)
  20. size, _ := dataReader.Read(mimeBuffer)
  21. if size > 0 {
  22. r.Header.Set("Content-Type", http.DetectContentType(mimeBuffer[:size]))
  23. return io.NopCloser(io.MultiReader(bytes.NewReader(mimeBuffer[:size]), dataReader))
  24. }
  25. return io.NopCloser(dataReader)
  26. }
  27. func urlEscapeObject(object string) string {
  28. t := urlPathEscape(removeDuplicateSlashes(object))
  29. if strings.HasPrefix(t, "/") {
  30. return t
  31. }
  32. return "/" + t
  33. }
  34. func entryUrlEncode(dir string, entry string, encodingTypeUrl bool) (dirName string, entryName string, prefix string) {
  35. if !encodingTypeUrl {
  36. return dir, entry, entry
  37. }
  38. return urlPathEscape(dir), url.QueryEscape(entry), urlPathEscape(entry)
  39. }
  40. func urlPathEscape(object string) string {
  41. var escapedParts []string
  42. for _, part := range strings.Split(object, "/") {
  43. escapedParts = append(escapedParts, strings.ReplaceAll(url.PathEscape(part), "+", "%2B"))
  44. }
  45. return strings.Join(escapedParts, "/")
  46. }
  47. func removeDuplicateSlashes(object string) string {
  48. result := strings.Builder{}
  49. result.Grow(len(object))
  50. isLastSlash := false
  51. for _, r := range object {
  52. switch r {
  53. case '/':
  54. if !isLastSlash {
  55. result.WriteRune(r)
  56. }
  57. isLastSlash = true
  58. default:
  59. result.WriteRune(r)
  60. isLastSlash = false
  61. }
  62. }
  63. return result.String()
  64. }
  65. func newListEntry(entry *filer_pb.Entry, key string, dir string, name string, bucketPrefix string, fetchOwner bool, isDirectory bool, encodingTypeUrl bool) (listEntry ListEntry) {
  66. storageClass := "STANDARD"
  67. if v, ok := entry.Extended[s3_constants.AmzStorageClass]; ok {
  68. storageClass = string(v)
  69. }
  70. keyFormat := "%s/%s"
  71. if isDirectory {
  72. keyFormat += "/"
  73. }
  74. if key == "" {
  75. key = fmt.Sprintf(keyFormat, dir, name)[len(bucketPrefix):]
  76. }
  77. if encodingTypeUrl {
  78. key = urlPathEscape(key)
  79. }
  80. listEntry = ListEntry{
  81. Key: key,
  82. LastModified: time.Unix(entry.Attributes.Mtime, 0).UTC(),
  83. ETag: "\"" + filer.ETag(entry) + "\"",
  84. Size: int64(filer.FileSize(entry)),
  85. StorageClass: StorageClass(storageClass),
  86. }
  87. if fetchOwner {
  88. listEntry.Owner = CanonicalUser{
  89. ID: fmt.Sprintf("%x", entry.Attributes.Uid),
  90. DisplayName: entry.Attributes.UserName,
  91. }
  92. }
  93. return listEntry
  94. }
  95. func (s3a *S3ApiServer) toFilerUrl(bucket, object string) string {
  96. object = urlPathEscape(removeDuplicateSlashes(object))
  97. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  98. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, object)
  99. return destUrl
  100. }
  101. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  102. bucket, object := s3_constants.GetBucketAndObject(r)
  103. glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
  104. if strings.HasSuffix(r.URL.Path, "/") {
  105. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  106. return
  107. }
  108. destUrl := s3a.toFilerUrl(bucket, object)
  109. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  110. }
  111. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  112. bucket, object := s3_constants.GetBucketAndObject(r)
  113. glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
  114. destUrl := s3a.toFilerUrl(bucket, object)
  115. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  116. }
  117. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, isWrite bool, responseFn func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int)) {
  118. glog.V(3).Infof("s3 proxying %s to %s", r.Method, destUrl)
  119. start := time.Now()
  120. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  121. if err != nil {
  122. glog.Errorf("NewRequest %s: %v", destUrl, err)
  123. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  124. return
  125. }
  126. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  127. proxyReq.Header.Set("Accept-Encoding", "identity")
  128. for k, v := range r.URL.Query() {
  129. if _, ok := s3_constants.PassThroughHeaders[strings.ToLower(k)]; ok {
  130. proxyReq.Header[k] = v
  131. }
  132. if k == "partNumber" {
  133. proxyReq.Header[s3_constants.SeaweedFSPartNumber] = v
  134. }
  135. }
  136. for header, values := range r.Header {
  137. proxyReq.Header[header] = values
  138. }
  139. // ensure that the Authorization header is overriding any previous
  140. // Authorization header which might be already present in proxyReq
  141. s3a.maybeAddFilerJwtAuthorization(proxyReq, isWrite)
  142. resp, postErr := s3a.client.Do(proxyReq)
  143. if postErr != nil {
  144. glog.Errorf("post to filer: %v", postErr)
  145. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  146. return
  147. }
  148. defer util_http.CloseResponse(resp)
  149. if resp.StatusCode == http.StatusPreconditionFailed {
  150. s3err.WriteErrorResponse(w, r, s3err.ErrPreconditionFailed)
  151. return
  152. }
  153. if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable {
  154. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
  155. return
  156. }
  157. if r.Method == http.MethodDelete {
  158. if resp.StatusCode == http.StatusNotFound {
  159. // this is normal
  160. responseStatusCode := responseFn(resp, w)
  161. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  162. return
  163. }
  164. }
  165. if resp.StatusCode == http.StatusNotFound {
  166. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  167. return
  168. }
  169. TimeToFirstByte(r.Method, start, r)
  170. if resp.Header.Get(s3_constants.SeaweedFSIsDirectoryKey) == "true" {
  171. responseStatusCode := responseFn(resp, w)
  172. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  173. return
  174. }
  175. if resp.StatusCode == http.StatusInternalServerError {
  176. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  177. return
  178. }
  179. // when HEAD a directory, it should be reported as no such key
  180. // https://github.com/seaweedfs/seaweedfs/issues/3457
  181. if resp.ContentLength == -1 && resp.StatusCode != http.StatusNotModified {
  182. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  183. return
  184. }
  185. if resp.StatusCode == http.StatusBadRequest {
  186. resp_body, _ := io.ReadAll(resp.Body)
  187. switch string(resp_body) {
  188. case "InvalidPart":
  189. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPart)
  190. default:
  191. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  192. }
  193. resp.Body.Close()
  194. return
  195. }
  196. setUserMetadataKeyToLowercase(resp)
  197. responseStatusCode := responseFn(resp, w)
  198. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  199. }
  200. func setUserMetadataKeyToLowercase(resp *http.Response) {
  201. for key, value := range resp.Header {
  202. if strings.HasPrefix(key, s3_constants.AmzUserMetaPrefix) {
  203. resp.Header[strings.ToLower(key)] = value
  204. delete(resp.Header, key)
  205. }
  206. }
  207. }
  208. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  209. for k, v := range proxyResponse.Header {
  210. w.Header()[k] = v
  211. }
  212. if proxyResponse.Header.Get("Content-Range") != "" && proxyResponse.StatusCode == 200 {
  213. w.WriteHeader(http.StatusPartialContent)
  214. statusCode = http.StatusPartialContent
  215. } else {
  216. statusCode = proxyResponse.StatusCode
  217. }
  218. w.WriteHeader(statusCode)
  219. buf := mem.Allocate(128 * 1024)
  220. defer mem.Free(buf)
  221. if n, err := io.CopyBuffer(w, proxyResponse.Body, buf); err != nil {
  222. glog.V(1).Infof("passthrough response read %d bytes: %v", n, err)
  223. }
  224. return statusCode
  225. }