You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

279 lines
8.2 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
5 years ago
4 years ago
4 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  7. "github.com/seaweedfs/seaweedfs/weed/s3api/s3acl"
  8. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  9. "io"
  10. "math"
  11. "mime"
  12. "net/http"
  13. "path/filepath"
  14. strconv "strconv"
  15. "strings"
  16. "time"
  17. "golang.org/x/exp/slices"
  18. "github.com/seaweedfs/seaweedfs/weed/filer"
  19. "github.com/seaweedfs/seaweedfs/weed/glog"
  20. "github.com/seaweedfs/seaweedfs/weed/images"
  21. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  22. "github.com/seaweedfs/seaweedfs/weed/stats"
  23. "github.com/seaweedfs/seaweedfs/weed/util"
  24. )
  25. // Validates the preconditions. Returns true if GET/HEAD operation should not proceed.
  26. // Preconditions supported are:
  27. //
  28. // If-Modified-Since
  29. // If-Unmodified-Since
  30. // If-Match
  31. // If-None-Match
  32. func checkPreconditions(w http.ResponseWriter, r *http.Request, entry *filer.Entry) bool {
  33. etag := filer.ETagEntry(entry)
  34. /// When more than one conditional request header field is present in a
  35. /// request, the order in which the fields are evaluated becomes
  36. /// important. In practice, the fields defined in this document are
  37. /// consistently implemented in a single, logical order, since "lost
  38. /// update" preconditions have more strict requirements than cache
  39. /// validation, a validated cache is more efficient than a partial
  40. /// response, and entity tags are presumed to be more accurate than date
  41. /// validators. https://tools.ietf.org/html/rfc7232#section-5
  42. if entry.Attr.Mtime.IsZero() {
  43. return false
  44. }
  45. w.Header().Set("Last-Modified", entry.Attr.Mtime.UTC().Format(http.TimeFormat))
  46. ifMatchETagHeader := r.Header.Get("If-Match")
  47. ifUnmodifiedSinceHeader := r.Header.Get("If-Unmodified-Since")
  48. if ifMatchETagHeader != "" {
  49. if util.CanonicalizeETag(etag) != util.CanonicalizeETag(ifMatchETagHeader) {
  50. w.WriteHeader(http.StatusPreconditionFailed)
  51. return true
  52. }
  53. } else if ifUnmodifiedSinceHeader != "" {
  54. if t, parseError := time.Parse(http.TimeFormat, ifUnmodifiedSinceHeader); parseError == nil {
  55. if t.Before(entry.Attr.Mtime) {
  56. w.WriteHeader(http.StatusPreconditionFailed)
  57. return true
  58. }
  59. }
  60. }
  61. ifNoneMatchETagHeader := r.Header.Get("If-None-Match")
  62. ifModifiedSinceHeader := r.Header.Get("If-Modified-Since")
  63. if ifNoneMatchETagHeader != "" {
  64. if util.CanonicalizeETag(etag) == util.CanonicalizeETag(ifNoneMatchETagHeader) {
  65. w.WriteHeader(http.StatusNotModified)
  66. return true
  67. }
  68. } else if ifModifiedSinceHeader != "" {
  69. if t, parseError := time.Parse(http.TimeFormat, ifModifiedSinceHeader); parseError == nil {
  70. if !t.Before(entry.Attr.Mtime) {
  71. w.WriteHeader(http.StatusNotModified)
  72. return true
  73. }
  74. }
  75. }
  76. return false
  77. }
  78. func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  79. path := r.URL.Path
  80. isForDirectory := strings.HasSuffix(path, "/")
  81. if isForDirectory && len(path) > 1 {
  82. path = path[:len(path)-1]
  83. }
  84. entry, err := fs.filer.FindEntry(context.Background(), util.FullPath(path))
  85. if err != nil {
  86. if path == "/" {
  87. fs.listDirectoryHandler(w, r)
  88. return
  89. }
  90. if err == filer_pb.ErrNotFound {
  91. glog.V(2).Infof("Not found %s: %v", path, err)
  92. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadNotFound).Inc()
  93. if r.Header.Get(s3_constants.XSeaweedFSHeaderAmzBucketAccessDenied) == "true" {
  94. w.WriteHeader(http.StatusForbidden)
  95. } else {
  96. w.WriteHeader(http.StatusNotFound)
  97. }
  98. } else {
  99. glog.Errorf("Internal %s: %v", path, err)
  100. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadInternal).Inc()
  101. w.WriteHeader(http.StatusInternalServerError)
  102. }
  103. return
  104. }
  105. //s3 acl offload to filer
  106. offloadHeaderBucketOwner := r.Header.Get(s3_constants.XSeaweedFSHeaderAmzBucketOwnerId)
  107. if len(offloadHeaderBucketOwner) > 0 {
  108. if statusCode, ok := s3acl.CheckObjectAccessForReadObject(r, w, entry, offloadHeaderBucketOwner); !ok {
  109. w.WriteHeader(statusCode)
  110. return
  111. }
  112. }
  113. query := r.URL.Query()
  114. if entry.IsDirectory() {
  115. if fs.option.DisableDirListing {
  116. w.WriteHeader(http.StatusForbidden)
  117. return
  118. }
  119. if query.Get("metadata") == "true" {
  120. writeJsonQuiet(w, r, http.StatusOK, entry)
  121. return
  122. }
  123. if slices.Contains([]string{"httpd/unix-directory", ""}, entry.Attr.Mime) {
  124. fs.listDirectoryHandler(w, r)
  125. return
  126. }
  127. // inform S3 API this is a user created directory key object
  128. w.Header().Set(s3_constants.X_SeaweedFS_Header_Directory_Key, "true")
  129. }
  130. if isForDirectory {
  131. w.WriteHeader(http.StatusNotFound)
  132. return
  133. }
  134. if query.Get("metadata") == "true" {
  135. if query.Get("resolveManifest") == "true" {
  136. if entry.Chunks, _, err = filer.ResolveChunkManifest(
  137. fs.filer.MasterClient.GetLookupFileIdFunction(),
  138. entry.GetChunks(), 0, math.MaxInt64); err != nil {
  139. err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error())
  140. writeJsonError(w, r, http.StatusInternalServerError, err)
  141. }
  142. }
  143. writeJsonQuiet(w, r, http.StatusOK, entry)
  144. return
  145. }
  146. etag := filer.ETagEntry(entry)
  147. if checkPreconditions(w, r, entry) {
  148. return
  149. }
  150. w.Header().Set("Accept-Ranges", "bytes")
  151. // mime type
  152. mimeType := entry.Attr.Mime
  153. if mimeType == "" {
  154. if ext := filepath.Ext(entry.Name()); ext != "" {
  155. mimeType = mime.TypeByExtension(ext)
  156. }
  157. }
  158. if mimeType != "" {
  159. w.Header().Set("Content-Type", mimeType)
  160. }
  161. // print out the header from extended properties
  162. for k, v := range entry.Extended {
  163. if strings.HasPrefix(k, "xattr-") {
  164. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  165. continue
  166. }
  167. if strings.HasPrefix(k, "Seaweed-X-") {
  168. // key with "Seaweed-X-" prefix is builtin and should not expose to user
  169. continue
  170. }
  171. w.Header().Set(k, string(v))
  172. }
  173. //Seaweed custom header are not visible to Vue or javascript
  174. seaweedHeaders := []string{}
  175. for header := range w.Header() {
  176. if strings.HasPrefix(header, "Seaweed-") {
  177. seaweedHeaders = append(seaweedHeaders, header)
  178. }
  179. }
  180. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  181. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  182. //set tag count
  183. tagCount := 0
  184. for k := range entry.Extended {
  185. if strings.HasPrefix(k, s3_constants.AmzObjectTagging+"-") {
  186. tagCount++
  187. }
  188. }
  189. if tagCount > 0 {
  190. w.Header().Set(s3_constants.AmzTagCount, strconv.Itoa(tagCount))
  191. }
  192. setEtag(w, etag)
  193. filename := entry.Name()
  194. adjustPassthroughHeaders(w, r, filename)
  195. totalSize := int64(entry.Size())
  196. if r.Method == "HEAD" {
  197. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  198. return
  199. }
  200. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  201. ext := filepath.Ext(filename)
  202. if len(ext) > 0 {
  203. ext = strings.ToLower(ext)
  204. }
  205. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  206. if shouldResize {
  207. data := mem.Allocate(int(totalSize))
  208. defer mem.Free(data)
  209. err := filer.ReadAll(data, fs.filer.MasterClient, entry.GetChunks())
  210. if err != nil {
  211. glog.Errorf("failed to read %s: %v", path, err)
  212. w.WriteHeader(http.StatusInternalServerError)
  213. return
  214. }
  215. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  216. io.Copy(w, rs)
  217. return
  218. }
  219. }
  220. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  221. if offset+size <= int64(len(entry.Content)) {
  222. _, err := writer.Write(entry.Content[offset : offset+size])
  223. if err != nil {
  224. stats.FilerRequestCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  225. glog.Errorf("failed to write entry content: %v", err)
  226. }
  227. return err
  228. }
  229. chunks := entry.GetChunks()
  230. if entry.IsInRemoteOnly() {
  231. dir, name := entry.FullPath.DirAndName()
  232. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  233. Directory: dir,
  234. Name: name,
  235. }); err != nil {
  236. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  237. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  238. return fmt.Errorf("cache %s: %v", entry.FullPath, err)
  239. } else {
  240. chunks = resp.Entry.GetChunks()
  241. }
  242. }
  243. err = filer.StreamContentWithThrottler(fs.filer.MasterClient, writer, chunks, offset, size, fs.option.DownloadMaxBytesPs)
  244. if err != nil {
  245. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  246. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  247. }
  248. return err
  249. })
  250. }