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.

238 lines
6.8 KiB

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