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.

268 lines
7.8 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"
  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. w.WriteHeader(http.StatusNotFound)
  93. } else {
  94. glog.Errorf("Internal %s: %v", path, err)
  95. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadInternal).Inc()
  96. w.WriteHeader(http.StatusInternalServerError)
  97. }
  98. return
  99. }
  100. //s3 acl offload to filer
  101. offloadHeaderBucketOwner := r.Header.Get(s3_constants.XSeaweedFSHeaderAmzBucketOwnerId)
  102. if len(offloadHeaderBucketOwner) > 0 {
  103. if statusCode, ok := s3acl.CheckObjectAccessForReadObject(r, w, entry, offloadHeaderBucketOwner); !ok {
  104. w.WriteHeader(statusCode)
  105. return
  106. }
  107. }
  108. query := r.URL.Query()
  109. if entry.IsDirectory() {
  110. if fs.option.DisableDirListing {
  111. w.WriteHeader(http.StatusForbidden)
  112. return
  113. }
  114. if query.Get("metadata") == "true" {
  115. writeJsonQuiet(w, r, http.StatusOK, entry)
  116. return
  117. }
  118. if entry.Attr.Mime == "" {
  119. fs.listDirectoryHandler(w, r)
  120. return
  121. }
  122. // inform S3 API this is a user created directory key object
  123. w.Header().Set(s3_constants.X_SeaweedFS_Header_Directory_Key, "true")
  124. }
  125. if isForDirectory {
  126. w.WriteHeader(http.StatusNotFound)
  127. return
  128. }
  129. if query.Get("metadata") == "true" {
  130. if query.Get("resolveManifest") == "true" {
  131. if entry.Chunks, _, err = filer.ResolveChunkManifest(
  132. fs.filer.MasterClient.GetLookupFileIdFunction(),
  133. entry.Chunks, 0, math.MaxInt64); err != nil {
  134. err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error())
  135. writeJsonError(w, r, http.StatusInternalServerError, err)
  136. }
  137. }
  138. writeJsonQuiet(w, r, http.StatusOK, entry)
  139. return
  140. }
  141. etag := filer.ETagEntry(entry)
  142. if checkPreconditions(w, r, entry) {
  143. return
  144. }
  145. w.Header().Set("Accept-Ranges", "bytes")
  146. // mime type
  147. mimeType := entry.Attr.Mime
  148. if mimeType == "" {
  149. if ext := filepath.Ext(entry.Name()); ext != "" {
  150. mimeType = mime.TypeByExtension(ext)
  151. }
  152. }
  153. if mimeType != "" {
  154. w.Header().Set("Content-Type", mimeType)
  155. }
  156. // print out the header from extended properties
  157. for k, v := range entry.Extended {
  158. if !strings.HasPrefix(k, "xattr-") {
  159. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  160. w.Header().Set(k, string(v))
  161. }
  162. }
  163. //Seaweed custom header are not visible to Vue or javascript
  164. seaweedHeaders := []string{}
  165. for header := range w.Header() {
  166. if strings.HasPrefix(header, "Seaweed-") {
  167. seaweedHeaders = append(seaweedHeaders, header)
  168. }
  169. }
  170. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  171. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  172. //set tag count
  173. tagCount := 0
  174. for k := range entry.Extended {
  175. if strings.HasPrefix(k, s3_constants.AmzObjectTagging+"-") {
  176. tagCount++
  177. }
  178. }
  179. if tagCount > 0 {
  180. w.Header().Set(s3_constants.AmzTagCount, strconv.Itoa(tagCount))
  181. }
  182. setEtag(w, etag)
  183. filename := entry.Name()
  184. adjustPassthroughHeaders(w, r, filename)
  185. totalSize := int64(entry.Size())
  186. if r.Method == "HEAD" {
  187. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  188. return
  189. }
  190. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  191. ext := filepath.Ext(filename)
  192. if len(ext) > 0 {
  193. ext = strings.ToLower(ext)
  194. }
  195. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  196. if shouldResize {
  197. data := mem.Allocate(int(totalSize))
  198. defer mem.Free(data)
  199. err := filer.ReadAll(data, fs.filer.MasterClient, entry.Chunks)
  200. if err != nil {
  201. glog.Errorf("failed to read %s: %v", path, err)
  202. w.WriteHeader(http.StatusInternalServerError)
  203. return
  204. }
  205. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  206. io.Copy(w, rs)
  207. return
  208. }
  209. }
  210. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  211. if offset+size <= int64(len(entry.Content)) {
  212. _, err := writer.Write(entry.Content[offset : offset+size])
  213. if err != nil {
  214. stats.FilerRequestCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  215. glog.Errorf("failed to write entry content: %v", err)
  216. }
  217. return err
  218. }
  219. chunks := entry.Chunks
  220. if entry.IsInRemoteOnly() {
  221. dir, name := entry.FullPath.DirAndName()
  222. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  223. Directory: dir,
  224. Name: name,
  225. }); err != nil {
  226. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  227. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  228. return fmt.Errorf("cache %s: %v", entry.FullPath, err)
  229. } else {
  230. chunks = resp.Entry.Chunks
  231. }
  232. }
  233. err = filer.StreamContentWithThrottler(fs.filer.MasterClient, writer, chunks, offset, size, fs.option.DownloadMaxBytesPs)
  234. if err != nil {
  235. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  236. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  237. }
  238. return err
  239. })
  240. }