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.

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